这部分主要设计实现一个基本的电话簿GUI界面。
头文件AddressBook.h
定义AddressBook的类。电话簿需要2个Qlabel标签(Name Address),2个输入域(相当于文本框)。
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = 0);
private:
QLineEdit *nameLine;
QTextEdit *addressText;
};
源文件AddressBook.cpp
AddressBook::AddressBook(QWidget *parent) :
QWidget(parent)
{
QLabel *nameLabel=new QLabel(tr("Name:"));
nameLine=new QLineEdit;
QLabel *addressLabel=new QLabel(tr("Address"));
addressText=new QTextEdit;
QGridLayout *mainLayout=new QGridLayout;
mainLayout->addWidget(nameLabel,0,0);
mainLayout->addWidget(nameLine,0,1);
mainLayout->addWidget(addressLabel,1,0,Qt::AlignTop);
mainLayout->addWidget(addressText,1,1);
setLayout(mainLayout);
setWindowTitle("Simple Address Book");
}
AddressBook::AddressBook(QWidget *parent) :QWidget(parent)
的意思是
The constructor of AddressBook accepts a QWidget parameter, parent. By convention, we pass this parameter to the base class’s constructor.
其实就是带参数的构造函数的初始化,遵循如下规则:
构造函数名(参数表):数据成员1(参数表),数据成员2(参数表)
Qwidget=parent,把parent参数传递给基类构造函数。
Main函数
修改Main函数如下:
#include "addressbook.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AddressBook addressbook;
addressbook.show();
return app.exec();
}
运行结果如图
Reference
[1].http://qt-project.org/doc/qt-4.8/tutorials-addressbook-part1.html