barjak
barjak

Reputation: 11270

Top-level Qt component does not expand when its content grows

In Qt, when the content of a widget grows (for example by adding more widgets in its layout), I expect the window to grow accordingly. This is even documented in an official tutorial as a window extension.

In my particular snippet of code, I can see that this extension does not happen. Instead, the window keeps its original size and the content becomes crushed.

#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>

class TestDialog : public QWidget
{
  Q_OBJECT
public:
  TestDialog() {
    layout = new QVBoxLayout;
    QLabel* lbl = new QLabel("This is a long label that word wraps");
    lbl->setWordWrap(true); // This line causes the problem
    layout->addWidget(lbl);
    QPushButton* btn = new QPushButton("Push me");
    layout->addWidget(btn);
    setLayout(layout);
    connect(btn, SIGNAL(clicked()), this, SLOT(addLabel()));
  }

private slots:
  void addLabel() {
    layout->addWidget(new QLabel("hey!"));
  }

private:
  QVBoxLayout* layout;
};

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  TestDialog* dialog = new TestDialog;
  dialog->show();
  return app.exec();
}

Initial state:

Base

Expected behavior after clicking the button:

enter image description here

Actual behavior after clicking the button:

enter image description here

The problem goes away when the call to setWordWrap is removed, but of course this is not what I want because I need to keep the word wrap behavior.

Also, I can also see the same behavior when I replace the wrapping Qlabel by a QCommandLinkButton that contains a description (the description text also has a word wrap behavior).

How can I combine the window extension behavior with the word wrapping behavior?

Upvotes: 1

Views: 50

Answers (1)

barjak
barjak

Reputation: 11270

You can achieve this by changing the size policy of the label widget.

lbl->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));

I am not sure what the cause of the issue is, though.

Upvotes: 0

Related Questions