1.解釋
QBoxLayout:可以在水平方向或垂直方向上排列控件,由QHBoxLayout、QVBoxLayout所繼承。
QHBoxLayout:水平布局,在水平方向上排列控件。
QVBoxLayout:垂直布局,在垂直方向上排列控件。
同時我們注意到水平布局、垂直布局除了構造時的方向(LeftToRight、TopToBottom)不同外,其它均相同。
2.示例代碼
2.1QHBoxLayout, QVBoxLayout實現
1 #include "widget.h" 2 #include <QApplication> 3 #include <QPushButton> 4 #include <QHBoxLayout> 5 #include <QVBoxLayout> 6 7 int main(int argc, char *argv[]) 8 { 9 QApplication a(argc, argv); 10 Widget w; 11 w.setWindowTitle("My App");//設置窗口標題 12 13 //創建3個Button 14 QPushButton *button1 = new QPushButton("one"); 15 QPushButton *button2 = new QPushButton("two"); 16 QPushButton *button3 = new QPushButton("three"); 17 18 QHBoxLayout *hlayout = new QHBoxLayout;//創建一個水平布局管理器 19 //將button加入水平布局器 20 hlayout->addWidget(button1); 21 hlayout->addWidget(button2); 22 hlayout->addWidget(button3); 23 24 QVBoxLayout *vlayout = new QVBoxLayout;//創建垂直布局器 25 //將button加入垂直布局器 26 vlayout->addWidget(button1); 27 vlayout->addWidget(button2); 28 vlayout->addWidget(button3); 29 30 w.setLayout(hlayout);//將水平布局器加入主窗口 31 //w.setLayout(vlayout);//將垂直布局器加入主窗口 32 33 w.show(); 34 35 return a.exec(); 36 }
2.2Functions
. setMargin(int)可以設置左、上、右、下的外邊距,設置之后,他們的外邊距是相同的。
. setContentsMargins(int left, int top, int right, int bottom)與其功能相同,但是可以將左、上、右、下的外邊距設置為不同的值。
. setContentsMargins(const QMargins &margins) 設置外邊距(同上)
. setSpacing(int) 間距設置
. addStretch()添加了一個伸縮空間(QSpacerItem)。
. setStretchFactor(QWidget *w, int stretch) , setStretchFactor(QLayout *l, int stretch) 設置控件、布局的拉伸系數