在進行佈局設置時,會用到layouts這個強大的佈局器。
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
QLabel *label = new QLabel(QApplication::translate("windowlayout", "Name:"));
QLineEdit *lineEdit = new QLineEdit();
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(label);
layout->addWidget(lineEdit);
window.setLayout(layout);
window.setWindowTitle(
QApplication::translate("windowlayout", "Window layout"));
window.show();
return app.exec();
}
代碼顯示:
代碼示例中,
QLabel *label = new QLabel(QApplication::translate("windowlayout", "Name:"));
QLineEdit *lineEdit = new QLineEdit();
這兩行代碼是創建一個標籤和行編輯器;
QHBoxLayout *layout = new QHBoxLayout();
這行代碼是創建一個佈局管理器
layout->addWidget(label);
layout->addWidget(lineEdit);
這兩行代碼是將兩個創建的label lineEdit 添加到layout去,再通過
window.setLayout(layout); 將label lineEdit兩個部件與windows進行子父類轉換(reparent),使這兩個部件變爲windows的子部件,否則,則會在運行時,顯示三個窗口。