要在 QML 中将 Text 放置在 Rectangle 中并使其居中,可以使用以下两种方法:

  1. 使用 anchors.centerIn 属性:将 Text 的 anchors.centerIn 设置为 Rectangle 的 anchors.center。这将使 Text 居中于 Rectangle。
Rectangle {
    width: 200
    height: 100
    color: 'lightblue'

    Text {
        text: 'Hello World'
        font.pixelSize: 20
        anchors.centerIn: parent
    }
}
  1. 使用 horizontalAlignment 和 verticalAlignment 属性:将 Text 的 horizontalAlignment 和 verticalAlignment 属性设置为 Text.AlignHCenter 和 Text.AlignVCenter。这将使 Text 水平和平直居中于 Rectangle。
Rectangle {
    width: 200
    height: 100
    color: 'lightblue'

    Text {
        text: 'Hello World'
        font.pixelSize: 20
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
    }
}

这两种方法都可以将 Text 居中于 Rectangle。根据实际需求选择适合的方法。

QML 中 Rectangle 内文字居中实现方法