Horizontal、Vertical、Grid Layouts
首先介紹最簡單的版面配置方法,那就是使用Qt提供的基本的版面組態管理:QHBoxLayout、QVBoxLayout與
QGridLayout。
這些類別是繼承自QLayout類別(再繼承自QObject類別)。這些類別主要負責widget版面位置的管理,經由這些版
面配置處理
可以產生更複雜的版面配置。
- QHBoxLayout將widget編排成水平的一列:
下列的程式碼建立一個QHBoxLayout,將5個QPushButton放置其中,其結果如圖所示:
QWidget *window = new QWidget;
QPushButton *button1 = new QPushButton("One");
QPushButton *button2 = new QPushButton("Two");
QPushButton *button3 = new QPushButton("Three");
QPushButton *button4 = new QPushButton("Four");
QPushButton *button5 = new QPushButton("Five");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);
window->setLayout(layout);
window->show();
- QVBoxLayout將widget編排成為垂直的一行:
QVBoxLayout的程式碼與上述的QHBoxLayout類似,其產生的結果如下:
- QGridLayout將widget編排成為二維的格子狀,widget可以佔據多個格子:
而使用QGridLayout則有些微不同,因為必須要指定widget的行與列位置。
QWidget *window = new QWidget;
QPushButton *button1 = new QPushButton("One");
QPushButton *button2 = new QPushButton("Two");
QPushButton *button3 = new QPushButton "Three");
QPushButton *button4 = new QPushButton("Four");
QPushButton *button5 = new QPushButton("Five");
QGridLayout *layout = new QGridLayout;
layout->addWidget(button1, 0, 0);
layout->addWidget(button2, 0, 1);
layout->addWidget(button3, 1, 0, 1, 2);
layout->addWidget(button4, 2, 0);
layout->addWidget(button5, 2, 1);
window->setLayout(layout);
window->show();
第三個QPushButton佔據了2行,所以在QGridLayout::addWidget()中指定了第五個參數2。
使用這種版面配置,
對child widget做版面配置時將不需要將parent widget參數引進來,此版面配置會自動利用QWidget::setParent()把Parent widget傳進來。
當使用者使用某個layout於這個視窗應用程式,而在這個layout中加入其他widget(譬如上例中的PushButton),則這些widget都自動成
為那個視窗應用程式使用此layout的child widget(記住,widget不能繼承自layout,只有widget之間才行)。
此外,你可以利用addLayout()在版面配置中再加入其他版面配置;addLayout()中加入的版面配置就會成為外面版面配置的child,
即可形成更複雜的版面配置。