Can I get the real width & height of a Text element?

qmldonkey picture qmldonkey · Apr 1, 2016 · Viewed 8.5k times · Source

I would like to get the real width & height of a Text element. If I use the paintedWidth & paintedHeight properties, I don't get it. For example:

Rectangle {
    color:  "green"
    width:  a_text.paintedWidth
    height: a_text.paintedHeight

    Text {
        id:     a_text
        text:   "r"
        color:  "white"
        anchors.centerIn: parent
    }
}

If I run that code, I see some green space on the left of the "r" on top of the "r" and below the "r". So I'm not getting the real width & height of the Text. I mean, the width & height of the white pixels.

Any way to do it?

P.S. Also I would need the relative position of the real top-left corner of the text, I mean, the x & y of the top-left white pixel relative to the "official" top-left pixel of the Text.

Answer

qmldonkey picture qmldonkey · Apr 4, 2016

The solution is to use the new TextMetrics element (requires QtQuick 2.5), and its tightBoundingRect property, to get the real width & heigth of the foreground text:

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