I want to find the space required for a text that I will draw later with QPainter. So I used QFontMetrics::boundingRect().

The problem is, boundingRect() wants me to tell it the answer first!

I tried QRect(0,0,0,0):

Qt Code:
  1. const QRect qBox = qMetrics.boundingRect(QRect(0,0,0,0), qAlign, qString, tabWidth);
To copy to clipboard, switch view to plain text mode 

This gives a reasonable answer only when the alignment is upperLeft.

When the alignment is anything else, the bounding rectangle returned is where the next line down would be. It kind of makes sense because there is not enough room for the text in QRect(0,0,0,0), so the text must be put down on the next line.

What can I specify for the QRect argument so that I get a reasonable result regardless of the text alignment?

When I have a QPainter instance handy, QPainter::boundingRect() does a fine job. It figures out that the text will not fit in the given QRect, and returns a QRect in which the text will fit:

Qt Code:
  1. const QRect qTextBBox(painter.boundingRect(QRect(0, 0, 0, 0), qAlign, qString));
To copy to clipboard, switch view to plain text mode 

But I need to get the bounding box when I have no QWidget, and therefore no QPainter. around.