#ifndef ADDRESSBOOK_H #define ADDRESSBOOK_H #include <QWidget> #include <QLineEdit> #include <QTextEdit> class AddressBook : public QWidget { Q_OBJECT public: AddressBook(QWidget *parent = 0); private: QLineEdit *nameLine; QTextEdit *addressText; }; #endif // ADDRESSBOOK_H
#include "addressbook.h" #include <QLabel> #include <QGridLayout> 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 Description Qt::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).
#include "addressbook.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); AddressBook addressBook; addressBook.show(); return a.exec(); }