就像小部件可以包含其他小部件一樣,佈局器可用於爲窗口小部件
怎麼實現圖片上的佈局呢?就要用到QHBoxLoyout QVBoxLayout QStandardItemModelQStandardItemModel 等函數。
在這裏,我們創建兩個layouts,queryLayout 它是一個 QHBoxLayout 包含兩個部件:QLabel QLineEdit 它們在上圖分兩列並排着,mainLayout 它是一個QVBoxLayout,這個部件包含一個QTableView 的組件,在上圖中窗口頂部。上菜:
#include
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();
}
上面代碼解釋:
QLabel *queryLabel = new QLabel(QApplication::translate(“nestedlayouts”, “Query:”));
QApplication::translate(“nestedlayouts”, “Query:”));
QLineEdit *queryEdit = new QLineEdit();
QTableView *resultView = new QTableView();
上面三行代碼是創建三個組件
QHBoxLayout 是一個能夠管理水平方向部件的管理器
QHBoxLayout 是一個能夠管理垂直方向部件的管理器
現在我們調用mainLayout的addLayout()函數將queryLayout插入到resultView表上方。
QStandardItemModel模型;
model.setHorizontalHeaderLabels(
QStringList中()<<的QApplication ::譯( “nestedlayouts”, “姓名”)
<< QApplication的翻譯::( “nestedlayouts”, “辦公室”));
的QList <QStringList中>行=的QList <QStringList中>()
<<(QStringList中()<< “凡爾納·尼爾森” << “123”)
<<(QStringList中()<< “卡洛斯·唐” << “77”)
<<(QStringList中()<< “布朗溫·霍克羅夫特” << “119”)
<<(QStringList中()<< “亞歷山德羅·漢森” << “32”)
<<(QStringList中()<< “安德魯·約翰·巴克肯” << “54”)
<<(QStringList中()<< “瓦內薩·韋瑟利” << “85”)
<<(QStringList中()<< “麗貝卡狄更斯” << “17”)
<<(QStringList中()<< “戴維·布拉德利” << “42”)
<<(QStringList中()<<“納特·沃爾特斯<< '25')
<<(QStringList中()<< “安德烈埃·瓊斯” << “34”);
的foreach(QStringList中排,行){
的QList <QStandardItem *>項;
的foreach(QString的文本,行)
items.append(新QStandardItem(文本));
model.appendRow(項目);
}
resultView->則setModel(模型);
resultView-> verticalHeader() - >隱藏();
resultView-> horizontalHeader() - > setStretchLastSection(真);