QT c++ 代码布局原则 简单例子

本文描述QT c++ widget代码布局遵循的原则:实中套虚,虚中套实。

本文最后列出了代码下载链接。

在QT6.2.4 msvc2019编译通过。

所谓实是实体组件:比如界面框、文本标签、组合框、文本框、按钮、表格、图片框等。

所谓虚是Layout组件:比如垂直布局、水平布局、网格布局、表单布局、堆栈布局。

所谓布局是指定排列规则。

1.界面

图1-界面效果

图2-布局关系示意

说明:图中的实线示意实体组件,虚线示意布局方式

2.代码

2.1界面类头文件

#ifndef WIDGET_H

#define WIDGET_H

#include <QWidget>

#include <QWidget>

#include <QGroupBox>

#include <QLabel>

#include <QLineEdit>

#include <QTextEdit>

#include <QPushButton>

QT_BEGIN_NAMESPACE

namespace Ui {

class Widget;

}

QT_END_NAMESPACE

class Widget : public QWidget

{

Q_OBJECT

public:

Widget(QWidget *parent = nullptr);

~Widget();

void initUI();

private:

Ui::Widget *ui;

QLabel * lb;

QGroupBox * gb;

QLineEdit * le;

QPushButton *btn1;

QTextEdit * txt;

};

#endif // WIDGET_H

2.2 cpp文件

#include "widget.h"

#include "ui_widget.h"

Widget::Widget(QWidget *parent)

: QWidget(parent)

, ui(new Ui::Widget)

{

ui->setupUi(this);

initUI();

}

void Widget::initUI()

{

QVBoxLayout * mainlayout = new QVBoxLayout(this);指定布局属于啥组件

lb =new QLabel(this);

lb->setText("自动");

gb=new QGroupBox();

QHBoxLayout *hboxlayout=new QHBoxLayout(gb);//指定布局属于啥组件

le=new QLineEdit(this);

le->setFixedWidth(100);

le->setFixedHeight(20);

btn1 = new QPushButton(this);

btn1->setFixedWidth(100);

btn1->setFixedHeight(20);

btn1->setText(tr("button1"));

hboxlayout->addWidget(le);//指定布局包含啥组件

hboxlayout->addWidget(btn1);//指定布局包含啥组件

// gb->setLayout(hboxlayout);//指定组件包含啥布局,因为上没有一行的参数是gb,本行可忽略

mainlayout->addWidget (lb);//指定布局包含啥组件

mainlayout->addWidget(gb);//指定布局包含啥组件

this->setLayout(mainlayout);

}

Widget::~Widget()

{

delete ui;

}

3.代码下载链接

https://download.csdn.net/download/weixin_39926429/89238564

相关推荐
朝朝辞暮i9 分钟前
第 01 讲:Python 变量、对象、数据类型与内存引用
开发语言·python
aqiu11111125 分钟前
【C++算法打怪专栏】LeetCode 217. 存在重复元素(解法总结)
c++·算法·leetcode
外收内放32 分钟前
Python基础语法练习题(69)
开发语言·python
lojox36 分钟前
深入理解 C++ STL:vector 底层实现、迭代器失效与 list 特性
开发语言·c++
iotxiaohu39 分钟前
用 cflow 查看 C 函数调用关系
c语言·开发语言·cflow
zhang-ge39 分钟前
python包和项目管理器uv在ubuntu下的安装与使用
开发语言·python·uv
微笑星河q1 小时前
C++类和对象(下)初始化列表、类型转换、static、友元、内部类、匿名对象
开发语言·c++
凤年徐2 小时前
【Python】Python 语法速通指南
开发语言·python
quantdash_cc2 小时前
量化数据清洗应该放在数据层还是策略层?从系统架构看清职责边界
开发语言·python·数据分析·系统架构·量化交易·股票数据·quantdash
|_⊙2 小时前
C++ 类和对象零散知识点
开发语言·c++