The easiest way to do it is to transfer the model items back and forth with a JS array, this way the JS JSON object functionality can be used to easily serialize and deserialize the data:import QtQuick 2.9import QtQuick.Controls 2.2import QtQuick.Window 2.3import Qt.labs.settings 1.0ApplicationWindow { id: main width: 640 height: 480 visible: true property string datastore: "" Component.onCompleted: { if (datastore) { dataModel.clear() var datamodel = JSON.parse(datastore) for (var i = 0; i < datamodel.length; ++i) dataModel.append(datamodel[i]) } } onClosing: { var datamodel = [] for (var i = 0; i < dataModel.count; ++i) datamodel.push(dataModel.get(i)) datastore = JSON.stringify(datamodel) } Settings { property alias datastore: main.datastore } ListView { id: view anchors.fill: parent model: ListModel { id: dataModel ListElement { name: "test1"; value: 1 } } delegate: Text { text: name + " " + value } } MouseArea { anchors.fill: parent acceptedButtons: Qt.LeftButton | Qt.RightButton onClicked: { if (mouse.button === Qt.LeftButton) { var num = Math.round(Math.random() * 10) dataModel.append({ "name": "test" + num, "value": num }) } else if (dataModel.count) { dataModel.remove(0, 1) } } }}应用程序以单个数据模型值开始,可以通过分别按鼠标左键和右键来添加或删除更多数据项.The application begins with a single data model value, more data items can be added or removed by pressing the left and right mouse button respectively.只要应用程序正常关闭,数据模型就会被复制到一个数组中,该数组将被序列化为一个字符串,由Settings元素存储.因此,在重新启动应用程序时,如果数据字符串存在,模型将被清除以删除初始值,因此它不会重复,数据字符串被反序列化回一个数组,该数组被迭代以恢复数据模型的内容.轻轻松松.As long as the application is closed properly, the data model will be copied into an array, which will be serialized to a string, which will be stored by the Settings element. So upon relaunching the app, if the data string is present, the model is cleared to remove the initial value so it is not duplicated, the data string is deserialized back into an array, which is iterated to restore the content of the data model. Easy peasy.当然,您也可以使用 LocalStorage API,甚至通过将 C++ 对象暴露给 QML 来编写一个简单的文件读取器和写入器.这种方法所需要的只是能够存储和检索单个字符串.Of course, you could also use the LocalStorage API as well, or even write a simple file reader and writer by exposing a C++ object to QML. All this approach needs is to be able to store and retrieve a single string. 这篇关于如何保存和恢复 ListModel 的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-30 00:01
查看更多