How to get the MultiLine QLabel‘s text real height?



  • Hi!
    I have a MultiLine QLabel ( use setWordWrap(multLine) ) . For some special reason, I must fix the QLabel's size. And I want to decrease the font size when the text real height heigher than QLabel's fixSize.(It means that adjust the FontSize to prevent the text which have long string to outside of label).
    I know to reimplement the resizeEvent , but I don't know how to get the MultiLine QLabel‘s text real height.
    Please give me some tips about how to get the MultiLine QLabel‘s text real height? Thanks in advance!


  • Qt Champions 2016

    @ljc123456gogo
    Hello,
    Maybe the QFontMetrics class could be useful, especially QFontMetrics::boundingRect?

    Kind regards.



  • @kshegunov

    Hello. I had used the QFontMetrics like:

    QFont f(font);
    f.setPixelSize( fontSize );
    QRect TextRect = QFontMetrics(f).boundingRect( this->text() );
    

    But it only get the SingleLine QLabel's text height. (Because it just refer the string and hadn't involve real text?)
    Is it my use way wrong?


  • Qt Champions 2016

    @ljc123456gogo
    That's because by default boundingRect will not expand the newlines (or tabs). Try something like this:

    static const int TabSize = 4;
    QFontMetrics metrics(font());
    QRect rect = metrics.boundingRect(QApplication::desktop()->geometry(), alignment() | Qt::TextWordWrap | Qt::TextExpandTabs, text(), TabSize);
    

    Note:
    If you don't have tabs, or don't wish to expand them, then don't pass Qt::TextExpandTabs as flag and TabSize as argument to the function.

    Note 2:
    If you in fact have a maximum rectangle that the text could occupy, pass that for the first argument instead of QApplication::desktop()->geometry(), e.g.:

    QRect rect = metrics.boundingRect(QRect(0, 0, maxWidth, maxHeight), alignment() | Qt::TextWordWrap | Qt::TextExpandTabs, text(), TabSize);
    // ... or the equivalent:
    QRect rect = metrics.boundingRect(0, 0, maxWidth, maxHeight, alignment() | Qt::TextWordWrap | Qt::TextExpandTabs, text(), TabSize);
    

    Kind regards.



  • @kshegunov
    It works! Thanks very much!


  • Qt Champions 2016

    @ljc123456gogo
    No problem! If the solution works for you, please mark the thread as "solved", thank you.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.