创建一个简易的窗口 1 2 3 4 5 6 7 8 9 int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; w.resize(800, 600); w.setWindowTitle("你好 服了"); w.show(); return a.exec(); } 使用布局 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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("草了"); window.show(); return app.exec(); } 上面在window上设置布局window.setLayout(layout)时,两个部件和布局本身都被 “重新父对象化”,成为窗口的子窗口。
qt嵌套布局 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; QLabel *queryLabel = new QLabel( QApplication::translate("nestedlayouts", "Query:")); QLineEdit *queryEdit = new QLineEdit(); QTableView *resultView = new QTableView(); QHBoxLayout *queryLayout = new QHBoxLayout();、 // 这里将queryLabel和queryEdit加入到布局中,但此时这些组件还没有父组件 queryLayout->addWidget(queryLabel); queryLayout->addWidget(queryEdit); QVBoxLayout *mainLayout = new QVBoxLayout(); // 将布局添加到另外一个布局时,则子布局的父对象是是其父布局 mainLayout->addLayout(queryLayout); mainLayout->addWidget(resultView); // 当给一个组件设置布局时,其布局内的所有组件都成为其子组件 // 但queryLayout的父组件还是mainLayout,这个关系没有发生改变 // mainLayout由于没有父布局,则其父组件变为了window window.setLayout(mainLayout); // Set up the model and configure the view... window.setWindowTitle( QApplication::translate("nestedlayouts", "Nested layouts")); window.show(); return app.exec(); } Qt元对象系统 元对象系统基于以下三个方面:
...