我有一个固定大小的矩形,它应该始终附着在窗口垂直中心的底部。如果窗口高度足够小,使得矩形能够接触边框,我想更改矩形的 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"
}
}
结果如下:
这工作得很好,但是每当我减小窗口大小以达到底部状态并再次增大窗口大小以达到居中状态时,我都会收到错误消息
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/