布局管理器
![在这里插入图片描述](https://img-blog.csdnimg.cn/c72b3a1caa08445a841e86a559b7dcc1.png)
利用布局管理器做出如下界面效果(标签与输入框设置伙伴关系):
![在这里插入图片描述](https://img-blog.csdnimg.cn/ed50e8583ffe4b7bb590b3a81b1e0b86.png)
新建桌面应用程序,项目名TestLayout,基类QWidget,类名Widget,不勾选创建界面。
#include "widget.h"
#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QFormLayout>
#include <QFont>
#include <QRadioButton>
#include <QPushButton>
#include <QSpacerItem>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
QFont font;
font.setFamily("黑体");
font.setPixelSize(14);
QLabel *nameLabel = new QLabel("姓名: (&N)");
QLabel *ageLabel = new QLabel("年龄: (&A)");
QLabel *emaiLabel = new QLabel("邮箱: (&E)");
QLabel *addrLabel = new QLabel("地址: (&R)");
QLabel *sexLabel = new QLabel("性别: ");
QLineEdit *nameEdit = new QLineEdit;
QLineEdit *ageEdit = new QLineEdit;
QLineEdit *emaiEdit = new QLineEdit;
QLineEdit *addrEdit = new QLineEdit;
//设置伙伴关系
nameLabel->setBuddy(nameEdit);
ageLabel->setBuddy(ageEdit);
emaiLabel->setBuddy(emaiEdit);
addrLabel->setBuddy(addrEdit);
//表单布局
QFormLayout *layout = new QFormLayout(&w);
layout->addRow(nameLabel, nameEdit);
layout->addRow(ageLabel, ageEdit);
layout->addRow(emaiLabel, emaiEdit);
layout->addRow(addrLabel, addrEdit);
//设置单选按钮布局
QFormLayout *sexLayout = new QFormLayout;
QRadioButton *radiMan = new QRadioButton("男");
QRadioButton *radiWoMan = new QRadioButton("女");
sexLayout->addRow(radiMan, radiWoMan); //先将按钮添加到一行里
layout->addRow(sexLabel, sexLayout); //再添加到主布局里
QHBoxLayout *hLayout = new QHBoxLayout;
QPushButton *pushBut = new QPushButton("确定");
QSpacerItem *hspacer = new QSpacerItem(150,20); //间隙
hLayout->addItem(hspacer); //添加间隙
hLayout->addWidget(pushBut); //添加按钮
layout->addRow(hLayout);
layout->setSpacing(15); //设置控件与控件间隙
layout->setMargin(15); //设置控件布局与窗体间隙
w.setFont(font);
w.show();
qDebug() << w.height();
qDebug() << w.width();
return a.exec();
}
最终运行效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/97e6ad502ea3433792c7eda92acc59af.png)