For Qt 4.6.x, how to auto-size text to fit in a specified width?

Posted by darenchow on Stack Overflow See other posts from Stack Overflow or by darenchow
Published on 2010-02-04T19:57:11Z Indexed on 2010/04/12 15:23 UTC
Read the original article Hit count: 260

Filed under:
|
|

Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width and similarly names can be of variable length.

Currently I am starting with a maximum font size, checking if it fits and decrementing it until I find a font size that fits. So far, I haven't been able to find a quick and easy way to do this. Is there a better, or more efficient way to do this?

Thanks!

void checkFontSize(QPainter *painter, const QString& name) {
 // check the font size - need a better algorithm... this could take awhile
 while (painter->fontMetrics().width(name) > rect().width()) {
  int newsize = painter->font().pointSize() - 1;
  painter->setFont(QFont(painter->font().family(), newsize));
 }
}

© Stack Overflow or respective owner

Related posts about qt

Related posts about autosize