与 TextMetrics 和此相关 question .
有没有办法准确地将矩形对齐以包围某些封闭的文本?我想要矩形和文本的像素精确对齐的原因是因为我想在某些图形(例如绘图)旁边绘制文本。
感谢下面的答案,我几乎已经将文本和矩形对齐,但仍然有几个像素的偏差,并且对齐方式似乎因平台而异。屏幕截图来自 OSX。
TextMetrics {
id: textMetrics
text: "TextSample72"
font.pointSize: 72
}
Rectangle {
width: textMetrics.tightBoundingRect.width
height: textMetrics.tightBoundingRect.height
color: "#bbbbdd"
z: 0
Text {
id: textSample72
text: "TextSample72"
font.pointSize: 72
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
verticalAlignment: Text.AlignBottom
z:1
}
}
最佳答案
TextMetrics
仅用于了解文本的宽度和高度,因为了解位置 x 和 y 没有意义,因为它仅分析所使用的字体。
在图像中,您可以看到文本存在垂直位移,并且该位移是由 anchor 引起的,在您的代码中,您指示它位于矩形的中心,但除此之外,您还指示上部与矩形的上部重合,如果字体的高度与矩形的高度不匹配(如本例所示),则通过在 y
中生成偏移量来强制其拉伸(stretch)。文本的位置。
一个可能的解决方案是将文本的对齐方式设置为 Text.AlignBottom
所以文本的高度和文本的高度没有区别,如果你想移动只需要在矩形中移动即可。
TextMetrics {
id: textMetrics
text: textSample72.text
font: textSample72.font
}
Rectangle {
y: 40 // if the rectangle is moved,
x: 40 // the text will also move
width: textMetrics.tightBoundingRect.width
height: textMetrics.tightBoundingRect.height
color: "#bbbbdd"
Text {
id: textSample72
text: "TextSample72"
verticalAlignment: Text.AlignBottom
font.pointSize: 72
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}
}
关于qt - 查找 Qt QML 文本元素的绘制 X 和 Y 位置(例如左上角),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51735551/