qt - 查找 Qt QML 文本元素的绘制 X 和 Y 位置(例如左上角)
问题描述
与 TextMetrics 和这个问题有关。
有没有办法准确对齐矩形以包围一些封闭的文本?我想获得矩形和文本的像素精确对齐的原因是因为我想在一些图形旁边绘制文本,例如绘图。
多亏了下面的答案,我几乎已经将文本和矩形对齐了,但仍然相差几个像素,并且对齐方式似乎因平台而异。屏幕截图来自 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 没有意义,因为它只分析使用的字体。
在图像中,您可以看到文本存在垂直位移,并且该位移是由锚点引起的,在您的代码中,您指示它在矩形中居中,但除此之外,您还指示上部部分与矩形的上部重合,如果字体的高度与矩形的高度不匹配(如本例所示),则通过y
在文本位置生成偏移量来强制它拉伸。
一种可能的解决方案是将文本的对齐方式设置为,Text.AlignBottom
这样文本的高度和文本的高度之间就没有区别,如果你想移动,只需在 Rectangle 中进行。
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
}
}
推荐阅读
- scala - Spark Kafka commitAsync 条件偏移?
- r - 我可以从 R 使用 MongoDB 执行原子事务吗?
- javascript - 排序图标不能替换 jquery ajax php
- node.js - 如何编译应用程序的一部分?
- python - 使 MyPy 正确检测 Enum 类中使用的描述符的类型
- php - 使用 Chrome 和资源管理器寻址服务器主机名时某些目录出现 HTTP 404 错误(IIS 上的 PHP)
- rdf - 如何压缩@id?
- c++ - 使用boost json ptree时如何检查null值
- r - 在训练数据上过度拟合,同时仍然改进验证数据
- service - ILE RPG 使用 CRTSQLRPGI 通过引用绑定