我想用代码实现布局,有一个QGroupBox,然后把控件放在里面,可以自适应布局的大小,代码如下:
baseWidget =new QWidget(this);
QGroupBox *group = new QGroupBox("Group",baseWidget);
QLabel *nameLabel=new QLabel(tr("Name"),baseWidget);
QLineEdit *nameEdit=new QLineEdit(baseWidget);
QLabel *sexLabel=new QLabel(tr("Sex"),baseWidget);
QComboBox *sexComboBox=new QComboBox(baseWidget);
sexComboBox->addItem(tr("male"));
sexComboBox->addItem(tr("female"));
QGridLayout *grid = new QGridLayout(group);
grid->addWidget(nameLabel,0,0);
grid->addWidget(nameEdit,0,1);
grid->addWidget(sexLabel,1,0);
grid->addWidget(sexComboBox,1,1);
grid->setSizeConstraint(QLayout::SetFixedSize);
baseWidget->setLayout(grid);
可是运行结果,那个group无法把控件都包起来,窗口的大小也不是自适应的,大家帮忙看下哪里有问题
------解决方案--------------------
#include "widget.h"
#include "ui_widget.h"
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QGridLayout>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QGroupBox *group = new QGroupBox("Group");
QLabel *nameLabel=new QLabel(tr("Name"));
QLineEdit *nameEdit=new QLineEdit();
QLabel *sexLabel=new QLabel(tr("Sex"));
QComboBox *sexComboBox=new QComboBox();
sexComboBox->addItem(tr("male"));
sexComboBox->addItem(tr("female"));
QGridLayout *grid = new QGridLayout();
grid->addWidget(nameLabel,0,0);
grid->addWidget(nameEdit,0,1);
grid->addWidget(sexLabel,1,0);
grid->addWidget(sexComboBox,1,1);
grid->setSizeConstraint(QLayout::SetFixedSize);
this->setLayout(grid);
}
Widget::~Widget()
{
delete ui;
}
这样,可以的。
------解决方案--------------------
应该是如下的层次结构:
BaseWidget -- VerticalLayout -- GruopBox -- GridLayout -- GroupBox的子窗口