使用Qt框架,如何测量使用给定字体/样式呈现的文本的宽度(以像素为单位)?
QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");
QFontMetrics fm(myFont);
int width=fm.width(str);
自Qt 5.11版本起,您必须使用QFontMetrics
类的horizontalAdvance()
方法,而不是width()
方法。 width()
现已过时。
QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");
QFontMetrics fm(myFont);
int width=fm.horizontalAdvance(str);
在 paintEvent 中
QString text("text");
QFontMetrics fm = painter.fontMetrics();
int width = fm.width(text);