获取 QPainter 绘制的文字尺寸

Get QPainter drawn text dimensions

我想使用 QPainter::drawText 命令绘制一些文本。

为了正确设置它的位置,我需要知道绘制的字符串的尺寸(以像素为单位)。

有没有办法知道字符串的像素尺寸?可能之前没画过?

QFontMetrics class 有一个方法就是为了这个目的:boundingRect().

来自 Qt 文档 (http://doc.qt.io/qt-5/qfontmetrics.html#boundingRect-2):

Returns the bounding rectangle of the characters in the string specified by text.

请注意,边界矩形 提供绘制文本的宽度,width() 函数也提供尾随空格的宽度。同样来自 Qt 文档:

boundingRect() returns a rectangle describing the pixels this string will cover whereas width() returns the distance to where the next string should be drawn.