qml - 使用状态时收到 'Cannot anchor to a null item'

标签 qml

我有一个固定大小的矩形,它应该始终附着在窗口垂直中心的底部。如果窗口高度足够小,使得矩形能够接触边框,我想更改矩形的 anchor ,使其粘在窗口的底部。

我使用状态实现了这一点:

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

结果如下:

Result (gif)

这工作得很好,但是每当我减小窗口大小以达到底部状态并再次增大窗口大小以达到居中状态时,我都会收到错误消息
qrc:/main.qml:14:5:QML 矩形:无法锚定到空项目。

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

最佳答案

您要确保使用 AnchorChanges处理 anchor 时而不是 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
                }
            }
        ]

关于qml - 使用状态时收到 'Cannot anchor to a null item',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71768533/

相关文章:

QT QmlMap 带点的折线

qt - 如何将 “this” 从 QML 元素传递给 JS 函数

opengl - 有没有人成功启动在 Qt 5.5(静态)和 msvc2015 中构建的 QML 应用程序

qt - 如何在 QWidget 中插入 QML View

c++ - 在 main.cpp 之外使用 QQuickView

python - 将循环变化的 python 变量暴露给 QML

qt - 通过 MouseArea 向 ChartView 添加橡皮筋缩放

c++ - Qt C++ 菜单栏在 Windows 上不显示,但在 Mac 上显示

qt - QML - 堆叠元素的不透明度

qt - 使用 QML 播放动画 SVG