Qt常用控件 | 布局管理器 | 水平布局Horizontal Layout
一、 QHBoxLayout介绍
1. 简介
QHBoxLayout(水平布局)是Qt中的一种布局管理器,用于在水平方向上排列子控件。它是QBoxLayout的一个子类。
使用QHBoxLayout可以将子控件按照从左到右的顺序排列,子控件之间的间距可以通过设置布局的spacing属性来调整。
2. 核心属性
属性 | 说明 |
layoutLeftMargin | 左侧边距 |
layoutRightMargin | 右侧边距 |
layoutTopMargin | 上⽅边距 |
layoutBottomMargin | 下⽅边距 |
layoutSpacing | 相邻元素之间的间距 |
二、 QHBoxLayout使用
1. 使用代码创建水平布局管理控件
- 编辑程序,创建三个按钮和一个水平布局,代码如下
#include "widget.h" #include "ui_widget.h" #include <QHBoxLayout> #include <QPushButton> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); //创建水平布局 QHBoxLayout * layout = new QHBoxLayout(); //创建三个按钮 QPushButton *button1 =new QPushButton("按钮1"); QPushButton *button2 =new QPushButton("按钮2"); QPushButton *button3 =new QPushButton("按钮3"); //将按钮设置到水平布局中 layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); //设置layout到widget中 this->setLayout(layout); } Widget::~Widget() { delete ui; }
2.运行代码,查看结果,如下图所示
2. 布局嵌套(垂直布局嵌套水平布局)
- 使用代码编写嵌套布局
#include "widget.h" #include "ui_widget.h" #include<QHBoxLayout> #include<QVBoxLayout> #include<QPushButton> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); // 创建顶层 layout QVBoxLayout* layoutParent = new QVBoxLayout(); this->setLayout(layoutParent); // 添加两个按钮进去 QPushButton* btn1 = new QPushButton("按钮1"); QPushButton* btn2 = new QPushButton("按钮2"); layoutParent->addWidget(btn1); layoutParent->addWidget(btn2); // 创建⼦ layout QHBoxLayout* layoutChild = new QHBoxLayout(); // 添加两个按钮进去 QPushButton* btn3 = new QPushButton("按钮3"); QPushButton* btn4 = new QPushButton("按钮4"); layoutChild->addWidget(btn3); layoutChild->addWidget(btn4); // 把这个⼦layout 添加到父layout 中 layoutParent->addLayout(layoutChild); } Widget::~Widget() { delete ui; }
2.行结果,查看结果
3. 图形化实现嵌套布局
- 使用图形化界面创建嵌套布局,在垂直布局中嵌套水平布局
- 运行代码,查看结果