Measuring text width in Qt


Question

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

1
47
8/26/2009 9:12:21 PM

Accepted Answer

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);
1
6/11/2019 1:06:14 PM

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon