【问题标题】:anchor.centerIn doesn't work as expected in my case在我的情况下,anchor.centerIn 无法按预期工作
【发布时间】:2022-01-23 14:49:36
【问题描述】:

我正在 QML 中创建一个组件,工作正常,但我希望 TEXT 字段位于矩形的中心。为此,我已相应地锚定它,但锚不起作用。我不知道为什么。

Item {

    id: root

    property int main_rect_height: 32
    property int elem_txt_size: 14
    property string elem_border_color: "red"
    property int elem_width: parent.width/6.5

    Rectangle {
        id: clients_rect
        width: root.parent.width-27
        height: main_rect_height
        color: "transparent"
        border.color: "black"

        Rectangle {
            id: username_rect
            width: elem_width
            height: parent.height
            color: "transparent"
            border.color: elem_border_color
            Text {
                id: username_txt
                text: "USERNAME"
                font.pixelSize: elem_txt_size
                anchors {
                    fill: parent
                    centerIn: parent    // THIS DOESN'T WORK!
                }
            }
        }
}

【问题讨论】:

  • 删除“填充:父”
  • 谢谢,它成功了。但是为什么当我填写父母时它不起作用?

标签: qt qml qtquick2


【解决方案1】:

通过使用anchors.fill: parent,您可以设置文本对象的大小和位置以匹配父对象。将相同大小的对象居中不会做任何事情,因为它已经占用了父对象的整个空间。默认情况下,文本顶部和左侧对齐。你有两个选择:

  1. 您可以使用 Text 的对齐属性将其自身内的文本对齐到居中:
Text {
    anchors.fill: parent
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
}
  1. 或者,您可以简单地使用 centerIn 而不使用 fill
Text {
    anchors.centerIn: parent
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多