QML中Loader加载的窗口无法识别嵌套ListView daylistView如何解决
问题根源
- QML的id作用域仅限当前组件的同一上下文,
daylistView是横向ListView的delegate内部定义的id,每个delegate实例都会生成独立的daylistView对象,本身就无法在delegate外直接通过id访问。 Loader加载的Window属于独立的窗口上下文,默认无法直接访问父组件上下文的对象,更不可能访问delegate内部的id。
解决方案
步骤1:给Loader添加自定义属性传递目标对象
修改Loader的定义,提前声明需要接收的属性,用来传递点击选中的daylistView实例和选中日期,避免跨上下文访问对象:
Loader { id:windowLoader focus: true active:false property ListView currentDayListView // 接收点击对应的纵向ListView实例 property var selectedDate // 传递选中的日期,避免跨上下文访问calendarMonth sourceComponent: Window{ id:inputWin title:"Enter Note" width:500 height:300 visible:true onClosing:{ windowLoader.active=false // 替换原daylistView为Loader传递的currentDayListView windowLoader.currentDayListView.currentIndex = windowLoader.selectedDate.getDate() === new Date().getDate() && windowLoader.selectedDate.getMonth() === new Date().getMonth()?getHour():12 } TextField { id:title x:50 y:20 placeholderText :'Enter Note' // 用Binding组件实现双向绑定,避免绑定断裂 Binding on text { value: windowLoader.active ? windowLoader.currentDayListView.currentItem.notetaking.text : "" } } TextField{ id:timeDate anchors.horizontalCenter: title.horizontalCenter anchors.top:title.bottom anchors.topMargin:10 placeholderText : windowLoader.selectedDate.getDate() +"-" + (windowLoader.selectedDate.getMonth()+1)+"-" + windowLoader.selectedDate.getFullYear() + " " + windowLoader.currentDayListView.currentItem.hourTime.text +":00" } Button { id: button text: qsTr("Add Note") anchors.centerIn:parent onClicked: { if (title.text !==""){ windowLoader.currentDayListView.currentItem.notetaking.text= title.text } } } } }
步骤2:修改MouseArea点击逻辑,传递对应实例
点击纵向ListView的条目时,把当前所属的daylistView实例和选中日期显式传递给Loader:
MouseArea{ anchors.fill:parent onClicked:{ daylistView.currentIndex=index // 显式传递当前delegate内的daylistView实例和选中日期 windowLoader.currentDayListView = daylistView windowLoader.selectedDate = calendarMonth.selectedDate windowLoader.active =true } }
注意事项
所有跨上下文使用的对象都需要通过属性显式传递,不要直接在独立Window中访问父上下文的id,即可彻底解决未定义报错和绑定失效问题。
内容的提问来源于stack exchange,提问作者cgiannakidis
相关产品推荐
相关产品推荐

