views:

528

answers:

4

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));
 }
}
A: 

Unfortunately, no. There's no easy solution to this. The most obvious improvement, performance-wise would be calculate and cache the needed font size when the text is changed instead of recalculating it in each paintEvent. Another improvement would be to try to estimate the correct size based on the proportions of the bounding rect. Making and testing estimates should get you to correct size much quicker than simply decrementing the point size by one each iteration.

Parker
+1  A: 

Johannes from qtcentre.org offered the following solution:

float factor = rect().width() / painter->fontMetrics().width(name);
 if ((factor < 1) || (factor > 1.25))
 {
  QFont f = painter->font();
  f.setPointSizeF(f.pointSizeF()*factor);
  painter->setFont(f);
 }

I gave it a try in my program and so far, it seems to work quite well. I like it because it produces results in one pass, but it assumes that font width scales like its height.

http://www.qtcentre.org/threads/27839-For-Qt-4-6-x-how-to-auto-size-text-to-fit-in-a-specified-width

A: 

You could have a QGraphicsTextItem as a child of the rect item, measure the text item's width and then scale the text item (setTransform()) to fit into the rect item's width (and height).

roop
A: 

This depends on the range over which you expect your font sizes to vary. If the range is large, incrementing by one may take a long time. If it's just a matter of several point sizes, speed probably won't be an issue.

If the range is large, another approach would be to add a larger interval, instead of '1'. If you exceed the desired size during one step, decrease the interval by, say, half. You'll bounce back and forth across the optimum size by smaller and smaller amounts each time; when the difference between two successive intervals is small, you can quit.

This is similar to the approach used in root finding. It may be overkill, since the size of fonts that will be acceptable to display in a given application is likely to be fairly narrow, and the brute force approach you're already using won't consume much time.

SixDegrees