Qt布局管理器

1. QVBoxLayout

QVBoxLayout表示垂直布局管理器

1.1 常用属性

属性 类型 读写性 说明 取值范围
layoutLeftMargin int 读写 布局的左侧边距,即布局与父容器左侧边缘之间的距离。通过设置该属性,可以控制布局在父容器中左侧的留白大小。 非负整数,单位为像素。值为 0 表示没有边距。
layoutRightMargin int 读写 布局的右侧边距,即布局与父容器右侧边缘之间的距离。用于控制布局在父容器中右侧的留白大小。 非负整数,单位为像素。值为 0 表示没有边距。
layoutTopMargin int 读写 布局的上方边距,即布局与父容器上侧边缘之间的距离。可调整布局在父容器中上方的留白大小。 非负整数,单位为像素。值为 0 表示没有边距。
layoutBottomMargin int 读写 布局的下方边距,即布局与父容器下侧边缘之间的距离。用于设置布局在父容器中下方的留白大小。 非负整数,单位为像素。值为 0 表示没有边距。
layoutSpacing int 读写 布局中相邻元素之间的间距,即垂直排列的子控件之间的垂直距离。能调整子控件之间的疏密程度。 非负整数,单位为像素。值为 0 表示子控件紧密排列。

1.2 例子1,使用代码创建

创建5个按钮,widget.cpp如下

Widget::Widget(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
   
   
    ui->setupUi(this);
    QPushButton* bt1 = new QPushButton("One");
    QPushButton* bt2 = new QPushButton("Two");
    QPushButton* bt3 = new QPushButton("Three");
    QPushButton* bt4 = new QPushButton("Four");
    QPushButton* bt5 = new QPushButton("Five");
    // 创建布局管理器,并将按钮添加进去,如果这里指定了parent为this,就不需要后面的setlayout了
    QVBoxLayout* layout = new QVBoxLayout();
    layout->addWidget(bt1);
    layout->addWidget(bt2);
    layout->addWidget(bt3);
    layout->addWidget(bt4);
    layout->addWidget(bt5);
    this->setLayout(layout); // 将一个布局管理器(QLayout 或其派生类的对象)关联到一个 QWidget 上
}

拖动窗口,按钮的位置和大小也会跟着变化

image-20250211143956199

1.3 例子2,使用Qt Designer

先拖入两个Vertical Layout,之后向里面拖入几个控件

image-20250211153121608

运行程序,发现拖动外部的窗口里面的两个Layout不会跟着变化

image-20250211153232075

事实上,一个widget只能设置一个layout布局,观察widget.ui可以发现这两个layout创建了两个QWidget,所以这两个layout不会跟着外部窗口的变化而变化

image-20250211153409583

2. QHBoxLayout

QHBoxLayout表示水平布局,属性与QVBoxLayout类似

2.1 例子1,基础使用

创建3个按钮,widget.cpp如下

Widget::Widget(QWidget *parent)
    : QWidget(parent)
      , ui(new Ui::Widget)
{
   
   
    ui->setupUi(this);
    QPushButton* bt1 = new QPushButton("One");
    QPushButton* bt2 = new QPushButton("Two");
    QPushButton* bt3 = new QPushButton("Three");
    // 创建布局管理器,并将按钮添加进去
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->addWidget(bt1);
    layout->addWidget(bt2);
    layout->addWidget(bt3);
}

运行结果如下

image-20250211155656987

2.2 例子2,嵌套使用

如果我们想实现如下的样式,需要嵌套使用这两种布局
image-20250211160259312

widget.cpp如下

Widget::Widget(QWidget *parent)
    : QWidget(parent)
      , ui(new Ui::Widget)
{
   
   
    ui->setupUi(this);
    QLineEdit* edit1 = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值