我能获得真正的宽度和宽度吗?文本元素的高度?

时间:2016-04-01 19:14:20

标签: qt qml qtquick2 plasmoid

我想得到真正的宽度& 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的高度。我的意思是,宽度&白色像素的高度。

有什么办法吗?

P.S。另外,我需要文本的真实左上角的相对位置,我的意思是,x&相对于"官方"的左上角白色像素的y Text的左上角像素。

2 个答案:

答案 0 :(得分:6)

解决方案是使用新的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
    }
}

答案 1 :(得分:1)

“your_text_object.paintedHeight”或“your_text_object.paintedWidth”:是获得文本高度所需要的,包括高度超过由于文本数量超出设定高度所覆盖的高度。

Text QML Element paintedHeight

相关问题