QFormLayout展开QGridLayout的列

时间:2018-09-06 16:54:15

标签: c++ qt qt5 qgridlayout qformlayout

我正在创建带有以下某些项目的QFormLayout:

QFormLayout *tableLayout = new QFormLayout();
QLineEdit *line1 = new QLineEdit();
QLineEdit *line2 = new QLineEdit();

tableLayout->addRow(tr("LineText1 "), line1);
tableLayout->addRow(tr("LineText2 "), line2);

之后,我尝试将这个布局添加到QGridLayout中,如下所示:

QGridLayout *layout = new QGridLayout();
QPushButton *btn1 = new QPushButton();
QPushButton *btn2 = new QPushButton();
layout->addWidget(btn, 1, 1, 3, 3);
layout->addWidget(btn2, 1, 4);
layout->addLayout(tableLayout, 2, 4);

添加tableLayout后,btn1的宽度为1列,而tableLayout的宽度为3列。

我已经尝试将QFormLayout放入自己的窗口小部件中,并将该窗口小部件添加到QGridLayout中。但这并没有改变任何东西。我这样做的方式如下:

QFormLayout *tableLayout = new QFormLayout();
QLineEdit *line1 = new QLineEdit();
QLineEdit *line2 = new QLineEdit();

tableLayout->addRow(tr("LineText1 "), line1);
tableLayout->addRow(tr("LineText2 "), line2);

QWidget *widget = new QWidget();
widget->setLayout(tableLayout);


QGridLayout *layout = new QGridLayout();
QPushButton *btn1 = new QPushButton();
btn1->setText("btn1");
QPushButton *btn2 = new QPushButton();
btn2->setText("btn2");
layout->addWidget(btn1, 1, 1, 3, 3);
layout->addWidget(btn2, 1, 4);
layout->addWidget(widget, 2, 4);

这种奇怪情况的原因是什么?以及如何解决?

以下是结果的图片:enter image description here

这就是我想要的水:enter image description here

1 个答案:

答案 0 :(得分:2)

要构建设计,您首先要确定元素的位置,请记住,行或列的位置从0开始,而不是从1开始。第二部分是设置大小策略,一些小部件已经有一些已建立的策略,例如QPushButton可以水平但不垂直地拉伸,因此即使rowSpan较大,它也不会更改按钮的高度,因此我们必须更改该行为最后是拉伸。

#include <QApplication>
#include <QFormLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QSizePolicy>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;

    QGridLayout *layout = new QGridLayout(&w);

    QPushButton *btn1 = new QPushButton("Btn1");
    btn1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    QPushButton *btn2 = new QPushButton("Btn2");
    btn2->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    QFormLayout *tableLayout = new QFormLayout();
    QLineEdit *line1 = new QLineEdit();
    QLineEdit *line2 = new QLineEdit();
    tableLayout->addRow("LineText1 ", line1);
    tableLayout->addRow("LineText2 ", line2);

    layout->addWidget(btn1, 0, 0, 3, 3);
    layout->addWidget(btn2, 0, 3);
    layout->addLayout(tableLayout, 1, 3);

    // column 0 x3
    layout->setColumnStretch(0, 3);
    // column 3 x1
    layout->setColumnStretch(3, 1);

    w.resize(640, 480);
    w.show();

    return a.exec();
}

enter image description here

请注意,QFormLayout将使小部件始终位于顶部,因此不一定占据QGridLayout提供的空间的高度。