【Qt 学习笔记】Qt常用控件 | 布局管理器 | 水平布局Horizontal Layout

简介: 【Qt 学习笔记】Qt常用控件 | 布局管理器 | 水平布局Horizontal Layout

Qt常用控件 | 布局管理器 | 水平布局Horizontal Layout

一、 QHBoxLayout介绍

1. 简介

QHBoxLayout(水平布局)是Qt中的一种布局管理器,用于在水平方向上排列子控件。它是QBoxLayout的一个子类。

使用QHBoxLayout可以将子控件按照从左到右的顺序排列,子控件之间的间距可以通过设置布局的spacing属性来调整。

2. 核心属性

属性 说明
layoutLeftMargin 左侧边距
layoutRightMargin 右侧边距
layoutTopMargin 上⽅边距
layoutBottomMargin 下⽅边距
layoutSpacing 相邻元素之间的间距


二、 QHBoxLayout使用

1. 使用代码创建水平布局管理控件

  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. 布局嵌套(垂直布局嵌套水平布局)

  1. 使用代码编写嵌套布局
#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. 图形化实现嵌套布局

  1. 使用图形化界面创建嵌套布局,在垂直布局中嵌套水平布局

  2. 运行代码,查看结果

目录
相关文章
【qt】 QGridLayout布局管理器怎么用?
【qt】 QGridLayout布局管理器怎么用?
775 0
【Qt 学习笔记】Qt窗口 | 标准对话框 | 消息对话框QMessageBox
【Qt 学习笔记】Qt窗口 | 标准对话框 | 消息对话框QMessageBox
2603 4
【Qt 学习笔记】Qt窗口 | 标准对话框 | 消息对话框QMessageBox
|
前端开发 程序员 API
【Qt】控件介绍
【Qt】控件介绍
|
开发者
【Qt 学习笔记】Qt系统相关 | Qt事件 | 事件的介绍及基本概念
【Qt 学习笔记】Qt系统相关 | Qt事件 | 事件的介绍及基本概念
672 4
【Qt 学习笔记】Qt窗口 | 标准对话框 | 文件对话框QFileDialog
【Qt 学习笔记】Qt窗口 | 标准对话框 | 文件对话框QFileDialog
4340 4
【Qt 学习笔记】Qt窗口 | 标准对话框 | 输入对话框QInputDialog
【Qt 学习笔记】Qt窗口 | 标准对话框 | 输入对话框QInputDialog
1727 3
|
数据可视化
【Qt 学习笔记】Qt窗口 | 标准对话框 | 字体对话框QFontDialog
【Qt 学习笔记】Qt窗口 | 标准对话框 | 字体对话框QFontDialog
722 3
【Qt 学习笔记】Qt窗口 | 标准对话框 | 颜色对话框QColorDialog
【Qt 学习笔记】Qt窗口 | 标准对话框 | 颜色对话框QColorDialog
3077 3
|
网络协议 Linux C++
【Qt】多种控件实现“hello world“
【Qt】多种控件实现“hello world“

推荐镜像

更多
  • qt