这里是一个简单的可扩展对话框的小例子:窗口可扩展,但是各部件的位置没有变化.
#include "c.h"
c::c(QWidget *parent)
: QWidget(parent)
{
// ui.setupUi(this);
QGridLayout *layout = new QGridLayout(this);
m_nameLabel = new QLabel(QString::fromLocal8Bit("姓名:"));
m_ageLabel = new QLabel(QString::fromLocal8Bit("年龄:"));
m_addressLabel = new QLabel(QString::fromLocal8Bit("家庭地址:"));
m_fatherLabel = new QLabel(QString::fromLocal8Bit("父亲:"));
m_motherLabel = new QLabel(QString::fromLocal8Bit("母亲:"));
m_nameLineEdit = new QLineEdit();
m_ageLineEdit = new QLineEdit();
m_addressLineEdit = new QLineEdit();
m_fatherLineEdit = new QLineEdit();
m_motherLineEdit = new QLineEdit();
m_sureButton = new QPushButton(QString::fromLocal8Bit("确定"));
m_detailButton = new QPushButton(QString::fromLocal8Bit("详细信息"));
m_detailButton->setCheckable(true);
layout->addWidget(m_nameLabel, 0, 0);
layout->addWidget(m_ageLabel, 1, 0);
layout->addWidget(m_addressLabel, 2, 0);
layout->addWidget(m_fatherLabel, 3, 0);
layout->addWidget(m_motherLabel, 4, 0);
layout->addWidget(m_nameLineEdit, 0, 1);
layout->addWidget(m_ageLineEdit, 1, 1);
layout->addWidget(m_addressLineEdit, 2, 1);
layout->addWidget(m_fatherLineEdit, 3, 1);
layout->addWidget(m_motherLineEdit, 4, 1);
layout->addWidget(m_sureButton, 1, 2);
layout->addWidget(m_detailButton, 2, 2);
m_fatherLineEdit->setVisible(false);
m_motherLineEdit->setVisible(false);
m_fatherLabel->setVisible(false);
m_motherLabel->setVisible(false);
//设置布局限制,保持固定的尺寸.
layout->setSizeConstraint(QLayout::SetFixedSize);
connect(m_detailButton, SIGNAL(toggled(bool)),this, SLOT(showDetailContentsSlot(bool)));
}
c::~c()
{
}
void c::showDetailContentsSlot(bool status)
{
if (status)
{
m_fatherLineEdit->setVisible(true);
m_motherLineEdit->setVisible(true);
m_fatherLabel->setVisible(true);
m_motherLabel->setVisible(true);
}
else
{
m_fatherLineEdit->setVisible(false);
m_motherLineEdit->setVisible(false);
m_fatherLabel->setVisible(false);
m_motherLabel->setVisible(false);
}
}
上面布局的示意图如下:只不过设置控件在布局中的位置.
下面是一些成员变量的定义.
#ifndef C_H
#define C_H
#include <QtWidgets/QWidget>
#include "ui_c.h"
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
class c : public QWidget
{
Q_OBJECT
public:
c(QWidget *parent = 0);
~c();
private slots:
void showDetailContentsSlot(bool);
private:
Ui::cClass ui;
QLabel *m_nameLabel;
QLabel *m_ageLabel;
QLabel *m_addressLabel;
QLabel *m_fatherLabel;
QLabel *m_motherLabel;
QLineEdit *m_nameLineEdit;
QLineEdit *m_ageLineEdit;
QLineEdit *m_addressLineEdit;
QLineEdit *m_fatherLineEdit;
QLineEdit *m_motherLineEdit;
QPushButton *m_sureButton;
QPushButton *m_detailButton;
};
#endif // C_H