建立头文件addressbook.h:
#ifndef ADDRESSBOOK_H#define ADDRESSBOOK_H#include#include #include class AddressBook : public QWidget{ Q_OBJECTpublic: AddressBook(QWidget *parent = 0);private: QLineEdit *nameLine; QTextEdit *addressText;};#endif // ADDRESSBOOK_H
建立源文件addressbook.cpp:
#include "addressbook.h"#include#include 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(tr("Simple Address Book"));}
AddressBook类继承自QWidget,“:QWidget(parent)”用来初始化父类。
这里使用了网格布局。其addWidget函数有两个原型:void QGridLayout::addWidget(QWidget * widget, int row, int column, Qt::Alignment alignment = 0)
void QGridLayout::addWidget(QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0)
参数含义显而易见。alignment需要多解释一下:
其默认值为0,说明添加的部件会填充满指定的网格。 Qt::AlignTop指明会将部件放在网格的上部。这些指定位置的常量还有:The horizontal flags are:Qt::AlignLeft : Aligns with the left edge.Qt::AlignRight : Aligns with the right edge.Qt::AlignHCenter : Centers horizontally in the available space.Qt::AlignJustify : Justifies the text in the available space.--------The vertical flags are:Constant Value DescriptionQt::AlignTop : Aligns with the top.Qt::AlignBottom : Aligns with the bottom.Qt::AlignVCenter : Centers vertically in the available space.--------You can use only one of the horizontal flags at a time. There is one two-dimensional flag:Qt::AlignCenter : Centers in both dimensions(AlignVCenter | AlignHCenter).
修改main.cpp:
#include "addressbook.h"#includeint main(int argc, char *argv[]){ QApplication a(argc, argv); AddressBook addressBook; addressBook.show(); return a.exec();}
运行结果: