目录

Qt常用控件之垂直布局QVBoxLayout

Qt常用控件之垂直布局QVBoxLayout

QVBoxLayout 是一种垂直布局控件。

属性说明
layoutLeftMargin左侧边距。
layoutRightMargin右侧边距。
layoutTopMargin顶部边距。
layoutBottomMargin底部边距。
layoutSpacing相邻元素间距。
方法说明
addWidget把控件添加到布局管理器。
setLayout设置布局管理器到……(即设置到 widget 中或其他 layout 中)

注意要将 QVBoxLayout 的父元素设置到 this 上,且 QVBoxLayout 头文件为 <QLayout>

#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include <QLayout>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QPushButton* button1=new QPushButton("pushButton1");
    QPushButton* button2=new QPushButton("pushButton2");
    QPushButton* button3=new QPushButton("pushButton3");

    QVBoxLayout* layout=new QVBoxLayout(this);
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
}

Widget::~Widget()
{
    delete ui;
}

https://i-blog.csdnimg.cn/img_convert/e8545d6e1179f56c1851654e70320121.png

代码构建的 layout 的特点是布局会随窗口大小变化而变化。