Tony the Pony
Tony the Pony

Reputation: 41357

Measuring text width in Qt

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

Upvotes: 59

Views: 40803

Answers (4)

Paul Dixon
Paul Dixon

Reputation: 300845

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

While this was correct 15 years ago when the question was asked, in later versions of Qt you'll need to use other methods - see later answers to this question.

Upvotes: 81

Sebastien247
Sebastien247

Reputation: 463

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

Upvotes: 25

Alexander
Alexander

Reputation: 510

In the paintEvent

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

Upvotes: 16

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506975

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.

Upvotes: 7

Related Questions