简体   繁体   English

在Qt中测量文本宽度

[英]Measuring text width in Qt

使用Qt框架,如何测量以给定字体/样式呈现的文本的宽度(以像素为单位)?

You can use QFontMetrics class - see the width() method which can give you the width of a given QString. 您可以使用QFontMetrics类-请参见width()方法,该方法可以为您提供给定QString的宽度。

QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");

QFontMetrics fm(myFont);
int width=fm.width(str);

In the paintEvent 在paintEvent中

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

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. 除了@Paul的答案外,我发现在绘制文本时(在Linux上为Qt4.8),与QFontMetrics::boundingRect返回的宽度相比,实际绘制的文本的宽度通常QFontMetrics::boundingRect关闭状态。 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 . 如果要在绘制文本时获得准确的结果(例如,在绘制文本的尺寸矩形上),最好使用QPainter直接提供的boundingRect函数。

Since Qt 5.11 you must use horizontalAdvance() method of QFontMetrics class instead of width() . 从Qt 5.11开始,您必须使用QFontMetrics类的horizontalAdvance()方法而不是width() width() is now obselete. width()现在已过时。

QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");

QFontMetrics fm(myFont);
int width=fm.horizontalAdvance(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM