Measuring text width in Qt
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);
In the paintEvent
QString text("text");
QFontMetrics fm = painter.fontMetrics();
int width = fm.width(text);
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);