QGridLayout的rowspan无法按预期工作

时间:2012-10-23 21:49:26

标签: c++ qt4 qgridlayout

以下是如何绘制一个跨越2列的按钮:

#include <QtGui>

int main(int argv, char **args)
{
    QApplication app(argv, args);

    QPushButton *foo = new QPushButton("foo");
    QPushButton *bar = new QPushButton("bar");
    QPushButton *baz = new QPushButton("baz");

    QGridLayout *layout = new QGridLayout();
    layout->addWidget(foo, 0, 0);
    layout->addWidget(bar, 0, 1);
    layout->addWidget(baz, 1, 0, 1, 2); // span 2 columns

    QWidget window;
    window.setLayout(layout);
    window.setWindowTitle("test");
    window.show();

    return app.exec();
}

运行代码给了我:

enter image description here

如果我更改布局以获得一个按钮baz,那么跨越2行我失败了:

layout->addWidget(foo, 0, 0);
layout->addWidget(bar, 1, 0);
layout->addWidget(baz, 0, 1, 2, 1); // (try to) span 2 rows

这是我得到的:

enter image description here

2 个答案:

答案 0 :(得分:4)

您的布局很好,baz按钮跨越两行。问题是它没有使用所有可用空间。您必须将按钮的垂直调整大小策略从Fixed更改为MinimumExpanding。

答案 1 :(得分:4)

我添加了以下内容,之后一切都很顺利:

 foo->setSizePolicy(QSizePolicy::MinimumExpanding,
                    QSizePolicy::MinimumExpanding);
 bar->setSizePolicy(QSizePolicy::MinimumExpanding,
                    QSizePolicy::MinimumExpanding);
 baz->setSizePolicy(QSizePolicy::MinimumExpanding,
                    QSizePolicy::MinimumExpanding);

thanks