0

I need to do a manual word wrap because the native wordWrap from Qt splits in wrong places. I've already done the wrap to my text, but the content wasn't showing all the content. The QLabel was cutting the top and the bottom like the image:

Can I fit the Qlabel to the height of the text inside it without wordWrap?

2 Answers2

1

I write it as height scalable :

QLabel lbl;
int count = 0;
QString str = "";

// set lbl text 
lbl.setText("hfdsf\ncsad\nfsc\dajkjkjkjhhkdkca\n925");
str = lbl.text();

for(int i = 0;i < str.length();i++)
    if(str.at(i).cell() == '\n')
        count++;

// resize lbl (width and height)
lbl.resize(lbl.fontMetrics().width("this is the max-length line in qlabel")
         , lbl.fontMetrics().height() * (count + 1));

Notice : this work if you change QLable font face or size! just in height scalable (before every thing set your QLabel frameShape to BOX).

if you want do width scalable-content, you should do these steps :

  • read QLabel(lbl object) text as line to line
  • calculate every line length
  • select maximum of line length
  • use of QLabel::fontMetrics().width(QString str) for investigate str size in width

I hope this can help you...

0

QLabel should resize automatically to the needed height if you place it in the layout, it does not matter if wordWrap is enabled or not, see the doc : http://doc.qt.io/qt-5/layout.html

ymoreau
  • 3,402
  • 1
  • 22
  • 60
  • @RafaelUeda Then you should check your layouts, maybe the sizePolicy of other widgets, because the `QLabel` preferred size will always fit your whole text height (even for multiple lines). I strongly discourage to use the solution of *Mohammadreza Panahi* because layouts allow you to do this automatically in a more flexible way, except if you have a very very specific use case. Playing yourself with the sizes is always a source of bugs and future limitations, very bad idea when you can avoid it. – ymoreau Dec 08 '17 at 08:54