布局管理器

image-20220116123759846

设计模式实现布局

详情见工具栏

image-20220116130800777

垂直布局,水平布局,打破布局。

代码实现布局

main.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "testlayout.h"
#include <QApplication>
#include<QLabel>
#include<QLineEdit>
#include<QFormLayout>
#include<QRadioButton>
#include<QVBoxLayout>
#include<QPushButton>
#include<QSpacerItem>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TestLayout w;
//添加部件并且布局
//添加标签
QLabel* nameLabel = new QLabel("姓名:(&N)");
QLabel* ageLabel = new QLabel("年龄:(&A)");
QLabel* emailLabel = new QLabel("邮箱:(&E)");
QLabel* doorLabel = new QLabel("门牌号码:");
// 添加文本框
QLineEdit* nameLineEdit = new QLineEdit;
QLineEdit* ageLineEdit = new QLineEdit;
QLineEdit* emailLineEdit = new QLineEdit;
QLineEdit* doorNumLineEdit = new QLineEdit;


//设置伙伴关系——绑定快捷键
nameLabel->setBuddy(nameLineEdit);
ageLabel->setBuddy(ageLineEdit);
emailLabel->setBuddy(emailLineEdit);
//添加布局
//QFormLayout常用语表单布局
QFormLayout* headerLayout = new QFormLayout;

//将部件添加到布局管理器中
headerLayout->addRow(nameLabel,nameLineEdit);
headerLayout->addRow(ageLabel,ageLineEdit);
headerLayout->addRow(emailLabel,emailLineEdit);
headerLayout->addRow(doorLabel,doorNumLineEdit);
//性别标签
QLabel* sexLabel = new QLabel("性别:");
//添加单选按钮
QRadioButton* mBtn = new QRadioButton;
QRadioButton* wBtn = new QRadioButton;
mBtn->setText("男");
wBtn->setText("女");
//添加水平布局管理器
QHBoxLayout* sexLayout = new QHBoxLayout;
sexLayout->addWidget(sexLabel);
sexLayout->addWidget(mBtn);
sexLayout->addWidget(wBtn);

//添加垂直布局管理器
//将两个布局管理器添加到一起
QVBoxLayout* mainLayout = new QVBoxLayout(&w);//参数-指定父窗体
mainLayout->addLayout(headerLayout);//添加布局
mainLayout->addLayout(sexLayout);
//在性别选项下添加空白
QSpacerItem* spacer = new QSpacerItem(30,30);
mainLayout->addItem(spacer);//添加空隙对象
//添加一个按钮
QPushButton* okBtn = new QPushButton("确定");
//将按钮添加到布局管理器中
mainLayout->addWidget(okBtn);//添加部件
mainLayout->setMargin(10);//与窗口的间隙
mainLayout->setSpacing(20);//设置控件间的间隙
//设置窗口布局管理器
w.setLayout(mainLayout);
w.show();
return a.exec();
}

image-20220116215432704