Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring text width in Qt

Tags:

c++

text

qt

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

like image 302
Tony the Pony Avatar asked Aug 26 '09 21:08

Tony the Pony


2 Answers

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); 
like image 94
Paul Dixon Avatar answered Sep 19 '22 04:09

Paul Dixon


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); 
like image 40
Sebastien247 Avatar answered Sep 21 '22 04:09

Sebastien247