查找 Qt QML 文本元素的绘制 X 和 Y 位置(例如左上角)

Find the Painted X and Y position (e.g. top left corner) of a Qt QML Text Element

与 TextMetrics 和此相关question。

有没有办法准确地对齐矩形以包围一些封闭的文本?我想要使​​矩形和文本精确对齐的原因是因为我想在某些图形(例如绘图)旁边绘制文本。

多亏了下面的回答,我几乎已经将文本和矩形对齐了,但仍然有几个像素的偏差,而且对齐方式似乎因平台而异。截图来自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
    }
}

TextMetrics 仅用于了解文本的宽度和高度,因为知道位置 x 和 y 没有意义,因为它仅分析所使用的字体。

在图像中,您可以看到文本存在垂直位移,该位移是由锚点引起的,在您的代码中,您表示它位于矩形的中心,但除此之外,您还还表明上部与矩形的上部重合,如果字体的高度与矩形的高度不匹配(如本例所示),您将通过在 y 文本的位置。

一个可能的解决方案是将文本的对齐方式设置为Text.AlignBottom,这样文本的高度和Text的高度之间就没有区别了,如果你想移动只需要做它在矩形中。

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