如何在currentIndex为-1时让StackLayout折叠?
解决StackLayout在currentIndex为-1时高度设为0的问题
你的Binding写法有误,QML的Binding元素需要通过target和property指定要绑定的对象与属性,而非直接在元素内写lay.height: 0。以下是几种可行的解决方案:
方法一:修正Binding写法
调整Binding元素的格式,明确指定目标对象、属性和绑定值:
Window { id: window width: 400 height: 400 visible: true color: "#181818" MouseArea { id: ma anchors.fill: parent hoverEnabled: true onClicked: lay.currentIndex = -1 } StackLayout { id: lay anchors.top: parent.top Rectangle { width: 300 height: 100 color: "white" } } // 修正后的Binding Binding { target: lay property: "height" value: 0 when: lay.currentIndex === -1 } Rectangle { anchors.top: lay.bottom width: 200 height: 100 color: "red" } }
方法二:直接绑定height属性
更简洁的方式是直接在StackLayout内部绑定height属性,无需单独的Binding元素:
StackLayout { id: lay anchors.top: parent.top // 当currentIndex为-1时高度设为0,否则使用默认隐式高度 height: currentIndex === -1 ? 0 : implicitHeight Rectangle { width: 300 height: 100 color: "white" } }
这里implicitHeight会自动获取StackLayout子项的默认高度,确保currentIndex不为-1时恢复原显示状态。
方法三:使用State管理状态
如果后续需要扩展更多状态切换逻辑,使用State会让代码结构更清晰:
Window { id: window width: 400 height: 400 visible: true color: "#181818" MouseArea { id: ma anchors.fill: parent hoverEnabled: true onClicked: lay.currentIndex = -1 } StackLayout { id: lay anchors.top: parent.top states: [ State { name: "collapsed" when: lay.currentIndex === -1 PropertyChanges { target: lay height: 0 } }, State { name: "expanded" when: lay.currentIndex !== -1 PropertyChanges { target: lay height: implicitHeight } } ] Rectangle { width: 300 height: 100 color: "white" } } Rectangle { anchors.top: lay.bottom width: 200 height: 100 color: "red" } }
内容的提问来源于stack exchange,提问作者Kamichanw
相关产品推荐
相关产品推荐

