QLabel sizehint is too small

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I have a QAbstractItemDelegate and in the paint method, I am trying to paint the text from a label. But the problem I am seeing is that the size hint of the QLabel is always too small for the text it contains. How can I fix this? For example:

QLabel *testlabel = new QLabel(); testlabel->setText("This is some test text that doesnt fit:"); testlabel->adjustSize();  QRect rect(testlabel->geometry()); Qt::Alignment alignFlags = testlabel->alignment();  painter->setFont(testlabel->font()); painter->drawRect(rect); painter->drawText(rect, alignFlags, testlabel->text()); 

And then it looks like:

Any ideas why the bounding rectangle is too small? Thanks Stephen

回答1:

If you are just trying to draw a bounding rectangle (or something related), you should get the painter's font metrics and ask for a bounding rectangle for the text you want to display. There are different versions of QFontMetrics::boundingRect that will allow you to specify a containing rectangle so word wrapping will be taken into consideration.



回答2:

why don't you use virtual QSize QLabel::sizeHint () const for getting the sizehint? it seems to be more reliable, because adjustSize();geometry() depends on the label being actually drawn onto something. but you don't draw the label (QWidget), but only it's text (QString), so adjustSize/geometry are more likely to fail than sizeHint.

see: http://doc.qt.io/qt-4.8/qwidget.html#sizeHint-prop

EDIT: oh, and using sizeHint would also simplify your code...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!