使用状态时接收 'Cannot anchor to a null item'

Receiving 'Cannot anchor to a null item' when using States

我有一个固定大小的矩形,它应该始终附着在 window 垂直中心的底部。如果 window 高度变得足够小,矩形可以触及边框,我想更改矩形的锚点,使其贴在 window 的底部。

我使用状态实现了这个:

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    id: window
    width: 200
    height: 480
    minimumHeight: maxSize
    visible: true

    property int maxSize: 150
    property bool centerTop: maxSize < (height / 2)

    Rectangle {
        id: rect

        states: [
            State {
                name: "Centered"
                when: centerTop
                PropertyChanges {
                    target: rect
                    anchors.top: parent.verticalCenter
                    anchors.bottom: undefined
                }
            },
            State {
                name: "Bottom"
                when: !centerTop
                PropertyChanges {
                    target: rect
                    anchors.top: undefined
                    anchors.bottom: parent.bottom
                }
            }
        ]
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.leftMargin: 10
        anchors.rightMargin: 10
        height: maxSize
        color: "red"
    }
}

结果是这样的:

这工作得很好,但每当我减小 window 大小以达到状态 Bottom 并再次增加它以达到状态 Centered 我收到错误消息
qrc:/main.qml:14:5: QML Rectangle: Cannot anchor to a null item.

我的问题有解决方案或更好的方法吗?

您要确保在处理锚点时使用 AnchorChanges 而不是 PropertyChanges。除了说:

之外,文档没有给出太多解释

PropertyChanges can be used to change anchor margins, but not other anchor values; use AnchorChanges for this instead.

        states: [
            State {
                name: "Centered"
                when: centerTop
                AnchorChanges {
                    target: rect
                    anchors.top: parent.verticalCenter
                    anchors.bottom: undefined
                }
            },
            State {
                name: "Bottom"
                when: !centerTop
                AnchorChanges {
                    target: rect
                    anchors.top: undefined
                    anchors.bottom: parent.bottom
                }
            }
        ]