C++ 在 Qt 中测量文本宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1337523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measuring text width in Qt
提问by Tony the Pony
Using the Qt framework, how do I measure the width (in pixels) of a piece of text rendered with a given font/style?
使用 Qt 框架,如何测量使用给定字体/样式呈现的一段文本的宽度(以像素为单位)?
采纳答案by Sebastien247
Since Qt 5.11 you must use horizontalAdvance()
method of QFontMetrics
class instead of width()
. width()
is now obselete.
从 Qt 5.11 开始,您必须使用类的horizontalAdvance()
方法QFontMetrics
而不是width()
. width()
现在已经过时了。
QFont myFont(fontName, fontSize);;
QString str("I wonder how wide this is?");
QFontMetrics fm(myFont);
int width=fm.horizontalAdvance(str);
回答by Paul Dixon
You can use QFontMetricsclass - 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);
回答by Alexander
In the paintEvent
在paintEvent中
QString text("text");
QFontMetrics fm = painter.fontMetrics();
int width = fm.width(text);
回答by Johannes Schaub - litb
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.
作为@Paul 回答的补充,我发现在绘制文本时(Linux 上的 Qt4.8),实际绘制的文本的宽度与QFontMetrics::boundingRect
返回的宽度相比通常是关闭的。就我而言,这幅画通常太宽了。
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
.
如果您绘制时文本(例如到尺寸矩形绘制文本周围)要准确的结果,最好使用boundingRect
由直接提供的功能QPainter
。