回观我们平时使用的软件界面,各个控件都是整齐分布,不是随意堆叠,为了方便和美观界面上各个组件的都有序分布,Qt的界面设计使用了布局功能,其就是指界面上组件的排列方式,使用布局可以使组件有规则地分布。
Qt提供了三个类以便我们布局使用,分别是:
- QHBoxLayout:水平排序布局
- QVBoxLayout:垂直排序布局
- QGridLayout:网格排序布局
水平布局和垂直布局继承于QBoxLayout类,统称线性布局,常用的方法有:
- void addLayout(QLayout layout, int stretch = 0) :在此布局结尾添加一个布局
- void addSpacerItem(QSpacerItem spacerItem) 、void addSpacing(int size) 、
void addStretch(int stretch = 0) :在此布局结尾添加一个间隔器
- void addWidget(QWidget *widget, int stretch = 0, Qt::Alignment alignment =Qt::Alignment()) :在此布局结尾添加一个QWidget,参数Qt::Alignment:可设置控件的对齐方向
- void setSpacing(int spacing) :设置布局中窗体之间的间距
- void setStretch(int index, int stretch) :设置布局中索引值为index的部件的占比
网格布局QGridLayout的常用方法:
- void addLayout(QLayout layout, int row, int column, Qt::Alignment alignment =Qt::Alignment())、void addLayout(QLayout *layout, int row, int column, int rowSpan, intcolumnSpan, Qt::Alignment alignment = Qt::Alignment()): 在行列添加一个QLayout 。并且占rowSpan行,columnSpan列。
- void addWidget(QWidget widget, int row, int column, Qt::Alignment alignment= Qt::Alignment())、void addWidget(QWidget *widget, int fromRow, int fromColumn, int rowSpan,int columnSpan, Qt::Alignment alignment = Qt::Alignment()) :在row行column列添加一个QWidget 。并且占rowSpan行,columnSpan列。
那么当我们所设计的界面中的控件特别多,而且为了方便管理和整洁美观,就需要组合使用,比如在水平布局中加入垂直布局,或者反过来也如此,就比如以下界面:
但无论使用水平还是垂直都需要组合使用,而这时我们就可以利用QGridLayout网格排序布局来达到以上所需两种布局组合使用的效果,而且可灵活分布组件位置。代码如下:
.h文件:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
void init();
};
#endif // DIALOG_H
.cpp文件:
#include "dialog.h"
#pragma execution_character_set("utf-8")
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QSpinBox>
#include <QGridLayout>
Dialog::Dialog(QWidget *parent) :
QDialog(parent)
{
resize(200,100);
init();
}
void Dialog::init()
{
QGridLayout *layout = new QGridLayout(this);
QLabel *nameLabel = new QLabel(tr("姓名:"));
QLineEdit *namelineEdit = new QLineEdit;
QLabel *sexLabel = new QLabel(tr("性别:"));
QComboBox *sexcomboBox = new QComboBox;
sexcomboBox->addItem("男");
sexcomboBox->addItem("女");
QLabel *ageLabel = new QLabel(tr("年龄:"));
QSpinBox *ageSpinBox = new QSpinBox;
ageSpinBox->setRange(1,99);
layout->addWidget(nameLabel,0,0);
layout->addWidget(namelineEdit,0,1,1,2);
layout->addWidget(sexLabel,1,0);
layout->addWidget(sexcomboBox,1,1,1,2);
layout->addWidget(ageLabel,2,0);
layout->addWidget(ageSpinBox,2,1,1,2);
}
Dialog::~Dialog()
{}