如何保存和还原ListModel的内容? [英] How to save and restore the content of a ListModel?

查看:240
本文介绍了如何保存和还原ListModel的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够保存使用Component.onComponent方法静态创建的列表项的设置.但是,重新打开应用程序后,静态创建的列表项的设置才会生效.我想保存动态创建的列表模型的设置.我无法保存动态创建的列表项的设置.下面的代码用于在单击显示/隐藏动作"时打开和关闭列表项.当我重新打开应用程序时,创建的列表项消失了.如何使用设置保存列表项?

I am able to save settings for list items which is statically created using Component.onComponent method. But Settings for statically created list items take affect after reopening app. I would like to save settings for dynamically created list model. I am unable to save Settings for a dynamically created list item. The code below does that a list item is on and off while clicking Show/Hide action. When I reopen the app, created list item disappears. How to save list item using Setting?

import QtQuick 2.9
import Fluid.Controls 1.0
import Qt.labs.settings 1.0
import QtQuick.Controls 1.4
ApplicationWindow {
    id:root
    visible: true
    width: 640
    height: 480
    property variant addlist
    property int countt2: 0
    Settings{
        id:mysetting4
        property alias ekranCosinus: root.countt2
    }
    function listonoff(){
        if(countt2%2==1){
            return true
          }
        else if(countt2%2==0){
            return false
        }
    }
    Connections {
        target: addlist

        onTriggered:   listonoff()

    }
    addlist: favourite2
    /* main.qml */
    menuBar: MenuBar {
            Menu {
                title: "&Edit"
                MenuItem { action: favourite2 }
            }
    }
    Action {
        id:favourite2
         text: qsTr("Show/Hide")
         onTriggered: {
            countt2++
            console.log(countt2)
               if(listonoff()===true){
                   return list_model.insert(list_model.index,{ title: "First item."} )
                }
                else if(listonoff()===false){
                   return list_model.remove(list_model.index)
                }
           }
        }
        ListView {
            id:contactlist
            width: parent.width
            height: parent.height
            focus: true
            interactive: true
            clip: true
            model: ListModel {
                id:list_model
            }
            delegate: ListItem {
                text: model.title
                height:60
            }
        }
        MouseArea {
            id: mouse
            anchors.fill: parent
        }
    }

推荐答案

您很好奇,您希望保存单个整数值将能够以某种方式存储任意数据模型的内容...甚至无法正常工作对于静态模型数据,它只是还原"的,因为它是静态的-它是代码的一部分,您实际上并没有保存和还原任何东西.

Quite curious that you expect that saving a single integer value will somehow be able to store the content of an arbitrary data model... It doesn't work even for the static model data, it is only "restored" because it is static - it is part of the code, you are not really saving and restoring anything.

如果要存储所有数据,则必须在应用退出时对其进行序列化,并在应用启动时对其进行反序列化.

If you want to store all that data, you will have to serialize it when your app quits, and deserialize it when the app starts.

您仍然可以使用Settings,但是要存储一个字符串值,它将代表序列化的数据.

You could still use Settings, but to store a string value, that will represent the serialized data.

最简单的方法是使用JS数组来回传输模型项,通过这种方式,可以使用JS JSON对象功能轻松地对数据进行序列化和反序列化:

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.9
import QtQuick.Controls 2.2
import QtQuick.Window 2.3
import Qt.labs.settings 1.0

ApplicationWindow {
  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的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆