如何在ListView外部暴露Model Index并传递给Switch组件?
解决方法
有两种常用方式可以将Model Index传递给外部定义的Switch组件:
方法一:通过Loader的上下文传递索引
在Loader中使用setContextProperty,将索引注入到加载组件的上下文里,这样Switch就能直接访问该索引:
ApplicationWindow { id: root visible: true width: 400 height: 400 Component { id: pinSwitch Switch { id: element text: qsTr("Switch") onToggled: { // 直接访问注入的itemIndex console.log("Switch Index", itemIndex, "is", checked ? "on" : "off") } } } ListView { id: pinListView Layout.fillWidth: true Layout.fillHeight: true clip: true model: FilterDelegateModel { id: filterDelegateModel model: pinModel delegate: Loader { id: controlLoader height: 30 sourceComponent: pinSwitch // 加载组件时注入索引,这里用DelegateModel.visibleIndex是过滤后的可视索引,若要原始模型索引用model.index Component.onCompleted: { setContextProperty("itemIndex", DelegateModel.visibleIndex) } } } } }
方法二:给Component定义属性,通过Loader传递
先给Switch所在的Component添加一个属性,再在Loader中绑定该属性到对应索引:
ApplicationWindow { id: root visible: true width: 400 height: 400 Component { id: pinSwitch // 定义属性接收外部传递的索引 property int itemIndex Switch { id: element text: qsTr("Switch") onToggled: { console.log("Switch Index", itemIndex, "is", checked ? "on" : "off") } } } ListView { id: pinListView Layout.fillWidth: true Layout.fillHeight: true clip: true model: FilterDelegateModel { id: filterDelegateModel model: pinModel delegate: Loader { id: controlLoader height: 30 sourceComponent: pinSwitch // 绑定属性到索引,同样可视索引用DelegateModel.visibleIndex,原始索引用model.index property int itemIndex: DelegateModel.visibleIndex } } } }
注意点
- 如果需要的是原始模型的索引(不受过滤影响),就用
model.index代替DelegateModel.visibleIndex;如果需要的是过滤后ListView中显示的顺序索引,就用DelegateModel.visibleIndex。
内容的提问来源于stack exchange,提问作者Clive N
相关产品推荐
相关产品推荐

