dadod2
dadod2

Reputation: 545

Label expands vertically in a QVBoxLayout

I have inserted a QLabel with a small sentence, a QLineEdit and a QPushButton, in this order, into a QVBoxLayout. My main window is 70% of the user's desktop.

My problem is that my label expands to nearly 80% of the parent window's height and the QLineEdit and the `QButton\ are squeezed at the bottom.

I figured out a way to solve this: I inserted more labels with no content but this can't be the golden solution. What can I do?

I also tried QFormLayout but it does not fit my needs. I like the widgets to be in a vertical order. I tried many ways with QSizePolicy but it did not work out.

Upvotes: 6

Views: 3573

Answers (1)

Mat
Mat

Reputation: 206699

I think what you're looking for is to add a spacer item. Try using addStretch on your layout after you've added all your widgets to it.

Example:

#include <QtGui>

class W: public QWidget
{
    Q_OBJECT

    public:
        W(bool spacer, QWidget *parent = 0)
            : QWidget(parent)
        {
            QLabel *l = new QLabel("Hello!");
            QLineEdit *e = new QLineEdit;
            QPushButton *p = new QPushButton("Go");

            QVBoxLayout *vl = new QVBoxLayout;
            vl->addWidget(l);
            vl->addWidget(e);
            vl->addWidget(p);

            if (spacer)
                vl->addStretch();

            setLayout(vl);

            resize(200, 400);
        }
};

Renders:

enter image description here

(No stretch on the left, stretch on the right.)

Upvotes: 8

Related Questions