布局

创建多个按钮布局

1.widget.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>

class Widget : public QWidget {
Q_OBJECT

public:
Widget(QWidget *parent = nullptr);
~Widget();

private:
// 多个按钮成员
QPushButton *m_btnSave;
QPushButton *m_btnCancel;
QPushButton *m_btnDelete;
};

#endif

2. widget.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "widget.h"
#include <QHBoxLayout> // 水平布局
#include <QDebug>

Widget::Widget(QWidget *parent) : QWidget(parent) {
setWindowTitle("布局管理器示例");
resize(300, 200);

// 1. 初始化按钮
m_btnSave = new QPushButton("保存 (Save)", this);
m_btnCancel = new QPushButton("取消 (Cancel)", this);
m_btnDelete = new QPushButton("删除 (Delete)", this);

// 2. 创建一个垂直布局管理器
// 设置 this 为父对象,表示该布局管理整个窗口的内容
QVBoxLayout *mainLayout = new QVBoxLayout(this);

// 3. 将按钮添加到布局中
mainLayout->addWidget(m_btnSave);
mainLayout->addWidget(m_btnCancel);
mainLayout->addWidget(m_btnDelete);

// 4. 添加一些间距和对齐(可选)
mainLayout->setSpacing(20); // 按钮之间的间距
mainLayout->setContentsMargins(50, 30, 50, 30); // 布局四周的留白

}

Widget::~Widget() {}

3. main.cpp

1
2
3
4
5
6
7
8
9
#include <QApplication>
#include "widget.h"

int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}

横向布局三个按钮

widget.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "widget.h"
#include <QHBoxLayout> // 核心修改:引入水平布局头文件
#include <QDebug>

Widget::Widget(QWidget *parent) : QWidget(parent) {
setWindowTitle("横向布局示例");
resize(500, 150); // 横向布局通常需要宽一点,矮一点

// 1. 初始化按钮
m_btnSave = new QPushButton("保存 (Save)", this);
m_btnCancel = new QPushButton("取消 (Cancel)", this);
m_btnDelete = new QPushButton("删除 (Delete)", this);

// 2. 创建水平布局管理器
// QHBoxLayout 会将控件从左到右依次排列
QHBoxLayout *mainLayout = new QHBoxLayout(this);

// 3. 将按钮添加到布局中
mainLayout->addWidget(m_btnSave);
mainLayout->addWidget(m_btnCancel);
mainLayout->addWidget(m_btnDelete);

// 4. 微调布局(可选)
mainLayout->setSpacing(10); // 按钮之间的水平间距
mainLayout->setContentsMargins(20, 20, 20, 20); // 四周留白

// 如果想让按钮靠左对齐,不撑满整个空间,可以加个弹簧:
// mainLayout->addStretch();

}

Widget::~Widget() {}