qlabel has wrong sizeHint() when wordwrap is enabled
Asked Answered
G

1

6

I have a custom QLabel with wordwrap enabled. When resizing MyWidget, it wraps but the sizeHint() still returns the original height. I tried the fix from this post: QLabel cutting off text on resize but the sizeHint() of the label still returns the initial height and results in cutoff text.

What do I have to do in order to get the TestLabel to return the correct sizeHint()?

    MyWidget::MyWidget(QWidget *parent)
    : QFrame(parent)
    {
        label = new TestLabel(this);
        label ->setWordWrap(true);
        label ->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        mLayout->addWidget(label);
    }


    void MyWidget::resizeEvent( QResizeEvent * event )
    {
       int height = label->heightForWidth(label->width());
       label->setMaximumHeight(height);
       //label->setMinimumHeight(height); // gets called all the time
       label->updateGeometry();
       QFrame::resizeEvent(event);
    }

the sizeHint() of the TestLabel class:

    QSize TestLabel::sizeHint() const
    {
       QSize s = QLabel::sizeHint();
       qDebug() << "sizeHint(): " << text() << ": " << s;
       return s;
    }

    QSize TestLabel::minimumSizeHint() const
    {
       QSize s = QLabel::sizeHint();
       qDebug() << "minimumSizeHint(): " << text() << ": " << s;
       return s;
    }
Goodale answered 8/4, 2013 at 19:50 Comment(1)
The sizeHint() is an indicator to the layout system as to how much space the widget would like to use if it had all the space in the world. Whether or not word wrapping is enabled has no effect on this, it just changes the behavior of the QLabel when it doesn't get the size it "asked" the layout for.Thayne
U
-1

Once I had problems with QLabel size hints - it was not updated after the QLabel text was changed, and I needed it immediately after text was changed (getting the text width using the font metrics doesn't give pixel-accurate size of the future label). There was a trick that helped me - I called invalidate() and activate() for all the layouts in the layout hierarchy containing that label - from the innermost to the outermost (exactly in that order). After that a call to the label's sizeHint() was returning the new and correct one. I remember that one of those 2 function was enough, I don't remember which one though. Layouts are quite a messy part in Qt, if you ever saw their codes.

Ulda answered 21/8, 2013 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.