Search code examples
qtcollectionsqmllistmodel

Collection of ListModel in QML


How can I create a Collection of ListModel Each list ListModel conatains 5 ListElement

ListModel{
    ListElement {
        type:"1"
        title:"5:03pm"
        description:"text-1"
        isLoaded: false   
    }
    ListElement {
        type:"1"
        title:"5:03pm"
        description:"text-1"
        isLoaded: false   
    }
    ListElement {
        type:"1"
        title:"5:03pm"
        description:"text-1"
        isLoaded: false   
    }
    ListElement {
        type:"1"
        title:"5:03pm"
        description:"text-1"
        isLoaded: false   
    }
    ListElement {
        type:"1"
        title:"5:03pm"
        description:"text-1"
        isLoaded: false   
    }
}

One model is like this . I want to create a qml with 2 or 3 ListModel collection

How can I create the collection.

Edit: I want to create the Collection of models dynamically. Each list model contains maximum 5 elements. once it reaches count 5 then I need to create another ListModel with elements. And so on.


Solution

  • Your collection would be represented by a property that is essentially a JS array. On inserting elements you check whether the collection doesn't contains a model, or if it does, whether the model already has 5 elements, if so you add another model to it, then append the item to the last model in the collection:

      id: main
      property var models: []
      Component {
        id: mod
        ListModel {}
      }
      function addItem(type, title, desc) {
        if (!models.length || models[models.length - 1].count > 4) models.push(mod.createObject(main))
        models[models.length - 1].append({"type": type, "title": title, "description": desc})
      }