2016-04-01 31 views
2

我想獲得Text元素的實際寬度&高度。如果我使用paintedWidth & paintedHeight屬性,我不明白。例如:我可以獲得Text元素的真實寬度和高度嗎?

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.此外,我還需要文本的實際左上角的相對位置,即,相對於Text的「官方」左上角像素的左上角白色像素的x &。

+0

我很高興你已經解決了你的問題 – BaCaRoZzo

回答

3

的解決方案是使用新的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 
    } 
} 
相關問題