我有一个固定大小的矩形,它应该始终附着在窗口垂直中心的底部。如果窗口高度足够小,使得矩形能够接触边框,我想更改矩形的锚点,使其粘在窗口的底部。
我使用状态实现了这一点:
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"
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
这工作得很好,但是每当我减小窗口大小以达到底部状态并再次增加窗口大小以达到居中状态时,我都会收到错误消息
qrc:/main.qml:14:5: QML Rectangle: Cannot anchor to a null item.
对于我的问题有解决方案或更好的方法吗?
您需要确保在处理锚点时使用AnchorChanges而不是 PropertyChanges。除了说之外,文档没有给出太多解释:
PropertyChanges 可用于更改锚点边距,但不能更改其他锚点值;请使用 AnchorChanges 来代替。
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
}
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
424 次 |
| 最近记录: |