Reputation: 2099
Related to TextMetrics and this question.
Is there a way to accurately align a rectangle to surround some enclosed text? The reason I would like to get pixel accurate alignment of the rectangle and the text is because I would like to paint the text next to some graphics, for example a plot.
Thanks to the answer below, I've almost got the text and the rectangle aligned, but it is still a few pixels off, and the alignment seems to vary across platforms. Screenshot is from OSX.
TextMetrics {
id: textMetrics
text: "TextSample72"
font.pointSize: 72
}
Rectangle {
width: textMetrics.tightBoundingRect.width
height: textMetrics.tightBoundingRect.height
color: "#bbbbdd"
z: 0
Text {
id: textSample72
text: "TextSample72"
font.pointSize: 72
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
verticalAlignment: Text.AlignBottom
z:1
}
}
Upvotes: 2
Views: 1058
Reputation: 243955
TextMetrics
only serves to know the width and height of the text since it would not make sense to know the position x and y since it only analyzes the font used.
In the image you can see that there is a vertical displacement of the text, and that displacement is caused by the anchors, in your code you are indicating that it is centered in the rectangle but in addition to it you are also indicating that the upper part coincides with the upper part of the rectangle, if the height of the font does not match the height of the rectangle (as in this case), you are forcing it to stretch by generating an offset in the y
position of the text.
A possible solution is to set the alignment of the text to Text.AlignBottom
so there would be no difference between the height of the text and the height of Text, and if you want to move just have to do it in the Rectangle.
TextMetrics {
id: textMetrics
text: textSample72.text
font: textSample72.font
}
Rectangle {
y: 40 // if the rectangle is moved,
x: 40 // the text will also move
width: textMetrics.tightBoundingRect.width
height: textMetrics.tightBoundingRect.height
color: "#bbbbdd"
Text {
id: textSample72
text: "TextSample72"
verticalAlignment: Text.AlignBottom
font.pointSize: 72
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}
}
Upvotes: 3