佈局layout
在Qt中,爲了實現特定的功能,一般情況下我們會使用的是自己定義的窗口類。
官方提供了Qt Create來編輯的ui文件,但是我不會使用操作編輯之後的ui,所以這裏介紹如何定義自己的佈局。
在QWidget中設置佈局
Qxxlayout類
若要佈局的窗口繼承自QWidget,那麼可以將佈局集成到一個Qxxlayout指針中,之後將這個layout綁定到當前的窗口即可。
Qxxlayout
分別有
- QGridLayout
可以在水平方向或垂直方向上排列控件,由QHBoxLayout、QVBoxLayout所繼承。
- QHBoxLayout
水平佈局,在水平方向上排列控件。
- QVBoxLayout
垂直佈局,在垂直方向上排列控件。
Qxxlayout中的函數
. 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)
設置控件、佈局的拉伸係數
將佈局用於當前窗口
this->setLayout(layout);
在QMainWindow中設置佈局
和QWidget
不同,在QMainWindow
中設置佈局的時候,需要:
- 先創建一個
widget
實例,並且將當前widget
實例設置爲當前窗口的setCentralWidget
- 然後設置
mainLayout
,然後將widget->setLayout(mainLayout);
widget = new QWidget();
this->setCentralWidget(widget);
//set the layout
widget->setLayout(mainLayout);