1
votes

I have a widget, I am using QVBoxLayout with the widget to organise rows of widgets. The first widget is a QLabel followed by multiple QPushButton widgets.

The width of each widget occupies 100% of the width, however the height of the first widget (QLabel) is much larger than the QPushButton widgets that follow it. All the QPushButtons are the same height.

It looks like the first row has been increased in size to pad the layout to fill the parent. If this is the case, is there any way to instruct the layout to use only the height required by the internal widgets and not to pad?

1

1 Answers

0
votes

The difference between the behavior of the layout for the QLabel and QPushButton is the sizePolicy, so the solution is to set the policy QSizePolicy::Maximum in the vertical part

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    QVBoxLayout *lay = new QVBoxLayout(&w);
    QLabel *label = new QLabel("Stack Overflow");
    label->setStyleSheet("background-color:salmon;");
    QSizePolicy sp = label->sizePolicy();
    sp.setVerticalPolicy(QSizePolicy::Maximum);
    label->setSizePolicy(sp);
    lay->addWidget(label);
    for (int i=0; i<4; i++) {
        lay->addWidget(new QPushButton(QString("pushbutton-%1").arg(i)));
    }
    w.show();
    return a.exec();
}