Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

qt - How to save and restore the content of a ListModel?

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
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...