【问题标题】:Can I get the real width & height of a Text element?我可以获得文本元素的真实宽度和高度吗?
【发布时间】:2016-04-01 19:14:19
【问题描述】:

我想获得Text 元素的实际宽度和高度。如果我使用 paintedWidthpaintedHeight 属性,我不明白。例如:

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 的真实宽度和高度。我的意思是,白色像素的宽度和高度。

有什么办法吗?

附:我还需要文本真正的左上角的相对位置,我的意思是,左上角白色像素相对于Text 的“官方”左上角像素的 x 和 y。

【问题讨论】:

  • 很高兴您解决了您的问题

标签: qt qml qtquick2 plasmoid


【解决方案1】:

解决方案是使用新的TextMetrics 元素(需要QtQuick 2.5)及其tightBoundingRect 属性,来获取前景文本的真实widthheigth

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
    }
}

【讨论】:

  • 注意:这并没有为我显示任何文本。必须将 anchors.fill: parent 添加到 Text 组件中。
【解决方案2】:

“your_text_object.paintedHeight”或“your_text_object.paintedWidth”:是获取文本高度所需的值,包括超过所覆盖高度的高度,因为文本超出了设置的高度。

Text QML Element paintedHeight

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2021-07-14
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2010-09-29
    • 2013-02-16
    相关资源
    最近更新 更多