部件教程--嵌套布局
正如部件可以包含其他部件一样,布局也可以用来为部件提供不同层次的分组。在这里,我们希望在窗口顶部显示一个标签和一个行编辑器,位于显示查询结果的表格视图上方。
为此,我们创建了两种布局:queryLayout
是一个QHBoxLayout ,包含并排放置的QLabel 和QLineEdit 部件;mainLayout
是一个QVBoxLayout ,包含垂直排列的queryLayout
和QTableView 部件。
#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(); queryLayout->addWidget(queryLabel); queryLayout->addWidget(queryEdit); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->addLayout(queryLayout); mainLayout->addWidget(resultView); window.setLayout(mainLayout); // Set up the model and configure the view... window.setWindowTitle( QApplication::translate("nestedlayouts", "Nested layouts")); window.show(); return app.exec(); } | ![]() |
请注意,我们调用mainLayout
的addLayout() 函数,将queryLayout
插入resultView
表格的上方。
我们省略了设置包含QTableView widget 所显示数据的模型resultView
的代码。为完整起见,我们将在下文中展示。
除了QHBoxLayout 和QVBoxLayout 之外,Qt XML 还提供了QGridLayout 和QFormLayout 类,以帮助实现更复杂的用户界面。运行Qt Widgets Designer 就能看到这些类。
设置模型
在上面的代码中,我们没有显示表格数据的来源,因为我们想把重点放在布局的使用上。在这里,我们可以看到模型中包含许多与行相对应的项,每个项都被设置为包含两列的数据。
QStandardItemModel model; model.setHorizontalHeaderLabels({ QApplication::translate("nestedlayouts", "Name"), QApplication::translate("nestedlayouts", "Office") }); const QStringList rows[] = { QStringList{ QStringLiteral("Verne Nilsen"), QStringLiteral("123") }, QStringList{ QStringLiteral("Carlos Tang"), QStringLiteral("77") }, QStringList{ QStringLiteral("Bronwyn Hawcroft"), QStringLiteral("119") }, QStringList{ QStringLiteral("Alessandro Hanssen"), QStringLiteral("32") }, QStringList{ QStringLiteral("Andrew John Bakken"), QStringLiteral("54") }, QStringList{ QStringLiteral("Vanessa Weatherley"), QStringLiteral("85") }, QStringList{ QStringLiteral("Rebecca Dickens"), QStringLiteral("17") }, QStringList{ QStringLiteral("David Bradley"), QStringLiteral("42") }, QStringList{ QStringLiteral("Knut Walters"), QStringLiteral("25") }, QStringList{ QStringLiteral("Andrea Jones"), QStringLiteral("34") } }; QList<QStandardItem *> items; for (const QStringList &row : rows) { items.clear(); for (const QString &text : row) items.append(new QStandardItem(text)); model.appendRow(items); } resultView->setModel(&model); resultView->verticalHeader()->hide(); resultView->horizontalHeader()->setStretchLastSection(true);
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.