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! -
@ljc123456gogo
Hello,
Maybe the QFontMetrics class could be useful, especially QFontMetrics::boundingRect?Kind regards.
-
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? -
@ljc123456gogo
That's because by defaultboundingRect
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 passQt::TextExpandTabs
as flag andTabSize
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 ofQApplication::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! -
@ljc123456gogo
No problem! If the solution works for you, please mark the thread as "solved", thank you.