我想获得 Text
的实际宽度和高度元素。如果我使用 paintedWidth
& paintedHeight
属性,没看懂例如:
Rectangle {
color: "green"
width: a_text.paintedWidth
height: a_text.paintedHeight
Text {
id: a_text
text: "r"
color: "white"
anchors.centerIn: parent
}
}
如果我运行该代码,我会在
"r"
的左侧看到一些绿色空间。在 "r"
之上和低于 "r"
.所以我没有得到 Text
的实际宽度和高度.我的意思是,白色像素的宽度和高度。有什么办法吗?
附言此外,我还需要文本真正左上角的相对位置,我的意思是,左上角白色像素的 x & y 相对于
Text
的“官方”左上角像素.
最佳答案
解决办法是使用新的TextMetrics
元素(需要 QtQuick 2.5)及其 tightBoundingRect
属性(property),得到真正的width
& heigth
前景文本:
import QtQuick 2.5 // required!
Rectangle {
color: "green"
width: t_metrics.tightBoundingRect.width
height: t_metrics.tightBoundingRect.height
Text {
id: a_text
text: "r"
color: "white"
anchors.centerIn: parent
}
TextMetrics {
id: t_metrics
font: a_text.font
text: a_text.text
}
}
关于qt - 我可以获得文本元素的实际宽度和高度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36364168/