Setting text on a QLabel in a layout, doesn't resize

TheDarkKnight picture TheDarkKnight · Oct 10, 2013 · Viewed 26.3k times · Source

Using the designer in Qt creator I have created a dialog that contains various widgets in a vertical layout. One of the widgets is a QLabel with word wrap set to true. The text for the QLabel is set just before the dialog is shown.

The maximum width and height of the QLabel is 16777215, the vertical size policy is set to Expanding and the horizontal is Preferred. I've tried changing changing the size policy.

The problem I have is that if the text is large, the QLabel fails to be adjusted accordingly and the text is clipped, like this: -

enter image description here

I have tried calling updateGeometry() for the dialog, after setting the text and also tried calling update on the vertical layout, but nothing appears to make any difference. Ideally, I want the QLabel to adjust vertically to accommodate the text.

Can someone tell me what I'm missing here?

Answer

thuga picture thuga · Oct 10, 2013

Set the vertical sizepolicy of your label to QSizePolicy::Minimum. Then set the sizeconstraint of your dialog's layout to QLayout::SetMinimumSize. This should make your dialog grow so all the content will fit inside of it.

Something like this:

QVBoxLayout *layout = new QVBoxLayout;
layout->setSizeConstraint(QLayout::SetMinimumSize);
this->setLayout(layout);
for(int i = 0; i < 5; i++)
{
    QLabel *label = new QLabel;
    label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    label->setWordWrap(true);
    label->setText("This is a very long text. This is a very long text. This is a very long text. "
                   "This is a very long text. This is a very long text. This is a very long text. This is a very long text. "
                   "This is a very long text. This is a very long text.");
    layout->addWidget(label);
}