我可以获得文本元素的实际宽度和高度吗?
Can I get the real width & height of a Text element?
我想获得 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"
的上方和 [=14= 的下方看到一些绿色的 space ].所以我没有得到 Text
的真实宽度和高度。我的意思是,白色像素的宽度和高度。
有什么办法吗?
P.S。此外,我还需要文本真正左上角的相对位置,我的意思是,左上角白色像素的 x 和 y 相对于 [=11= 的 "official" 左上角像素].
解决方法是使用新的TextMetrics
元素(需要QtQuick 2.5),以及它的tightBoundingRect
属性,得到真正的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
}
}
"your_text_object.paintedHeight" 或 "your_text_object.paintedWidth":是获取文本高度所需要的,包括超过由于文本多于设置高度而被覆盖的高度的高度。
我想获得 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"
的上方和 [=14= 的下方看到一些绿色的 space ].所以我没有得到 Text
的真实宽度和高度。我的意思是,白色像素的宽度和高度。
有什么办法吗?
P.S。此外,我还需要文本真正左上角的相对位置,我的意思是,左上角白色像素的 x 和 y 相对于 [=11= 的 "official" 左上角像素].
解决方法是使用新的TextMetrics
元素(需要QtQuick 2.5),以及它的tightBoundingRect
属性,得到真正的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
}
}
"your_text_object.paintedHeight" 或 "your_text_object.paintedWidth":是获取文本高度所需要的,包括超过由于文本多于设置高度而被覆盖的高度的高度。