Measuring text width in Qt

C++QtText

C++ Problem Overview


Using the Qt framework, how do I measure the width (in pixels) of a piece of text rendered with a given font/style?

C++ Solutions


Solution 1 - C++

You can use QFontMetrics class - see the width() method which can give you the width of a given QString.

QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");

QFontMetrics fm(myFont);
int width=fm.width(str);

Solution 2 - C++

Since Qt 5.11 you must use horizontalAdvance() method of QFontMetrics class instead of width(). width() is now obselete.

QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");

QFontMetrics fm(myFont);
int width=fm.horizontalAdvance(str);

Solution 3 - C++

In the paintEvent

QString text("text");
QFontMetrics fm = painter.fontMetrics();
int width = fm.width(text);

Solution 4 - C++

As an addition to the answer by @Paul, I found that when painting text (Qt4.8 on linux), the width of an actually painted text compared to the width of what QFontMetrics::boundingRect returns is often off. In my cases, the painting was often too wide.

If you want accurate results when painting text (for example to dimension rectangles you draw around text), better use the boundingRect functions provided directly by QPainter.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony the PonyView Question on Stackoverflow
Solution 1 - C++Paul DixonView Answer on Stackoverflow
Solution 2 - C++Sebastien247View Answer on Stackoverflow
Solution 3 - C++AlexanderView Answer on Stackoverflow
Solution 4 - C++Johannes Schaub - litbView Answer on Stackoverflow