QML中的Listmodel:如何在页面堆栈中的页面切换上保留Listmodel值

我有一个XML文件来显示项目列表(listview),点击我切换到每个项目的页面,使用pagestack.push读取每个类别的XMLListmodel。

按下后再次转到同一页面导致ListModel数据丢失。

如何在不丢失ListModel数据信息的情况下将代码模块化为多个QML文件。

请告诉我。

附加示例代码段。

main.qml

if(currentPageName == "menuName") { PageStack.push(Qt.resolvedUrl("showChosenList.qml")); } 

showChosenList.qml

  ListModel{ id: hotelMainMenuModel } XmlListModel { id: hotelMainMenuFetch source: "hotelMenu.xml" query: "/hotelMenu/menuCategories/categoryList/mainMenu" onStatusChanged: { if (status === XmlListModel.Ready) { for (var i = 0; i < count; i++) { hotelMainMenuModel.append({"name": get(i).name, "displayText": get(i).name, "pageName": get(i).pageName}) } } } XmlRole { name: "name"; query: "name/string()" } XmlRole { name: "pageName"; query: "pageName/string()" } } } 

我相信你的问题是每次向文件夹推送一个文件名会创建一个新对象,而这个新对象不会与之前创建的任何对象共享数据。 而是在您的顶级QML文件中创建要推送的页面实例,并在每次显示时将其推送到页面堆栈。

这是一个我希望说明正在发生的事情的例子。

main.qml

 import QtQuick 2.0 import Ubuntu.Components 0.1 MainView { width: units.gu(50) height: units.gu(75) PageStack { id: pageStack Page { id: page title: "Top Page" visible: false Column { anchors.fill: parent Button { width: parent.width text: "Open page from object" onClicked: pageStack.push(subPage) } Button { width: parent.width text: "Open page from file" onClicked: pageStack.push(Qt.resolvedUrl("SubPage.qml")) } } } SubPage { // This is an instance of the object declared in SubPage.qml. All you need // to do to make this work is have SubPage.qml in the same directory as // this QML file. id: subPage visible: false } Component.onCompleted: pageStack.push(page) } } 

SubPage.qml

 import QtQuick 2.0 import Ubuntu.Components 0.1 Page { title: "SubPage" Component.onCompleted: console.log("Made a new page") Button { width: parent.width property int count: 0 text: "Clicked %1 times".arg(count) onClicked: count += 1 } } 

请注意,当您在页面堆栈中来回移动时,从对象加载的页面上的计数器仍然存在,而从文件加载的页面在每次加载时将计数器设置为0。 此外,后者每次都会将完成事件记录到控制台,而前者仅在程序启动时记录此事件。