Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
qmldonkey Avatar asked Apr 01 '16 19:04

qmldonkey


2 Answers

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
    }
}
like image 116
qmldonkey Avatar answered Sep 16 '22 15:09

qmldonkey


"your_text_object.paintedHeight" or "your_text_object.paintedWidth": is what you need to get the height of the text, including height past the height which is covered due to there being more text than fits in the set height.

Text QML Element paintedHeight

like image 20
Adriano Campos Avatar answered Sep 18 '22 15:09

Adriano Campos