首页 > 解决方案 > 查找 Qt QML 文本元素的绘制 X 和 Y 位置(例如左上角)

问题描述

与 TextMetrics 和这个问题有关

有没有办法准确对齐矩形以包围一些封闭的文本?我想获得矩形和文本的像素精确对齐的原因是因为我想在一些图形旁边绘制文本,例如绘图。

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

在此处输入图像描述

标签: qttextqmlmetrics

解决方案


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

在图像中,您可以看到文本存在垂直位移,并且该位移是由锚点引起的,在您的代码中,您指示它在矩形中居中,但除此之外,您还指示上部部分与矩形的上部重合,如果字体的高度与矩形的高度不匹配(如本例所示),则通过y在文本位置生成偏移量来强制它拉伸。

一种可能的解决方案是将文本的对齐方式设置为,Text.AlignBottom这样文本的高度和文本的高度之间就没有区别,如果你想移动,只需在 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
    }
}

在此处输入图像描述


推荐阅读