Qt入門 佈局管理器layout(三)

佈局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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章