Qt QML PathView轮播选中首尾项时如何隐藏对应首尾子项
报错原因
报错中的Value指itemAtIndex(0)的返回值。
你给PathView配置了pathItemCount: 3,这个属性会限制PathView最多同时渲染路径可见范围内的3个delegate实例,不在可见范围内的index对应item不会被创建,调用itemAtIndex()取这类不存在的item就会返回null,你直接访问null的visible属性就触发了该类型错误。即便你调试确认count和currentIndex是有效值,只要对应index的item不在渲染范围内,就会拿到null。
正确实现方式
推荐用QML声明式绑定的方案,完全避免空对象访问问题:
- 删除你现在写的
onCurrentIndexChanged里的item操作逻辑 - 修改delegate声明,在内部绑定visible属性即可:
delegate: DelegateContent { visible: { // 选中最后一项时隐藏第一个子项 if (view.currentIndex === view.count - 1) { return index !== 0 } // 选中第一项时隐藏最后一个子项 if (view.currentIndex === 0) { return index !== view.count - 1 } // 其余场景全部可见 return true } }
如果你一定要沿用命令式操作item的写法,先加非空判断即可:
onCurrentIndexChanged: { // 控制第一个item可见性 const firstItem = itemAtIndex(0) if (firstItem) { firstItem.visible = currentIndex < (count - 1) } // 控制最后一个item可见性 const lastItem = itemAtIndex(count - 1) if (lastItem) { lastItem.visible = currentIndex > 0 } }
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

