1

What is the best way to determine if text-size exceeds width of QLabel? And according to that, change the text-size?

I have a QLabel with word-wrap option set to true, but when text is so long it is being cropped from left and right side.

  • 1
    Is your label widget managed by a layout? If so, you should set the `sizeConstraint` on the topmost layout (`label->widnow()->layout()`), so that the window will be always sufficiently large to hold all of the contents. – Kuba hasn't forgotten Monica Mar 31 '16 at 12:22

1 Answers1

2

You might want to try this approach:

QLabel label;
QRect r = label.fontMetrics().boundingRect( "My text" ) );
int textWidth = r.width();
vahancho
  • 19,049
  • 3
  • 36
  • 47
  • @Hcorg, The text's width does not depend on QLabel's properties. – vahancho Mar 31 '16 at 12:15
  • yes, I know. I meant - it will not work for label that can hold multiple lines of text, broken using word-wrap. For single line label fontMetrics()....width() compared to label.width() should help. – Hcorg Mar 31 '16 at 12:18
  • I tried to manage text size according to label size in my answer to [SO: How to automatically increase/decrease text size in label in Qt](http://stackoverflow.com/questions/42652738/how-to-automatically-increase-decrease-text-size-in-label-in-qt/42690033?s=2|4.1672#42690033). Thereby, I realized that [`QFontMetrics::boundingRect()`](http://doc.qt.io/qt-5/qfontmetrics.html#boundingRect-2) provided in-accurate results. Digging deeper, I found a more precise calculation duplicating internal calculations of `QLabel` which can be found there. So, I think it's worth to be mentioned here. – Scheff's Cat May 11 '17 at 08:58