【发布时间】:2022-11-05 06:54:05
【问题描述】:
我正在尝试使用 PySide6 的 QPainter 和 QFontMetrics 绘制多段文本。我想以与将它们全部绘制在一个文本块中相同的间距来绘制它们,但是行间距不太正确。
在下面的示例中,字体度量表明字体的行距为 17。当我测量单行文本时,边界矩形确实是 17 像素高。但是,当我测量两行文本时,边界矩形是 35 像素高,而不是 34 像素。多余的像素是从哪里来的,我可以在字体的某些属性或字体度量上看到它吗?
from PySide6.QtGui import QFont, QFontMetrics
from PySide6.QtWidgets import QApplication
app = QApplication()
font = QFont()
metrics = QFontMetrics(font)
print(metrics.lineSpacing()) # 17
print(metrics.boundingRect(0, 0, 100, 100, 0, 'A').height()) # 17
print(metrics.boundingRect(0, 0, 100, 100, 0, 'A\nB').height()) # 35 != 17 * 2
print(metrics.leading()) # 0
print(metrics.ascent()) # 14
print(metrics.descent()) # 3
顺便说一句,它并不总是一个额外的像素。如果我把字体变大,额外的空间就会增加。
更新
我以为我已经通过从QFontMetrics 切换到QFontMetricsF 的musicamante's suggestion 解决了这个问题,但还是有区别的。
from PySide6.QtCore import QRectF
from PySide6.QtGui import QFont, QFontMetricsF
from PySide6.QtWidgets import QApplication
app = QApplication()
font = QFont()
metrics = QFontMetricsF(font)
print(metrics.height()) # 16.8125
print(metrics.boundingRect(QRectF(0, 0, 100, 100),
0,
'A').getCoords()) # (0.0, 0.0, 9.9375, 16.8125)
print(metrics.boundingRect(QRectF(0, 0, 100, 100),
0,
'A\nB').getCoords()) # (0.0, 0.0, 9.9375, 34.8125)
# Note the height of that rect doesn't match the next calculation.
print(metrics.height() + metrics.lineSpacing()) # 34.046875
# I can't see any combination of these numbers that makes 34.8125
print(metrics.lineSpacing()) # 17.234375
print(metrics.leading()) # 0.421875
print(metrics.ascent()) # 13.984375
print(metrics.descent()) # 2.828125
【问题讨论】: