QFormLayout 扩展 QGridLayout 的列

QFormLayout expands column of QGridLayout

我正在创建一个包含如下项目的 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);

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

这是结果的图片:

这是我想要的:

要构建您想要的设计,首先要确定元素的位置,请记住行或列的位置从 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();
}

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