Qt入门 布局管理器layout(三)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010468553/article/details/79637548

布局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);

猜你喜欢

转载自blog.csdn.net/u010468553/article/details/79637548