How to add element for QML ListModel using Javascript?

12,435

Use subAlpha.append(). This method takes a Javascript object as an argument, which it uses to create a new ListElement with those keys and values.

A working example:

import QtQuick 2.0

ListView {
    width: 200
    height: 200

    ListModel {
        id: mainModel
        ListElement {
            name: "Alphabet"
            subAlpha: [
                ListElement {
                    alphaName: "A"
                },
                ListElement {
                    alphaName: "B"
                }
            ]
        }
    }

    model: mainModel
    delegate: Column {
        Text { text: name }
        Row {
            Repeater {
                model: subAlpha
                Text { text: alphaName }
            }
        }
    }

    Component.onCompleted: {
        mainModel.get(0).subAlpha.append({alphaName: "C"})
    }
}
Share:
12,435

Related videos on Youtube

A.P.
Author by

A.P.

Updated on September 18, 2022

Comments

  • A.P.
    A.P. almost 2 years

    I have created one nested ListModel.

    ListModel {
        id: mainModel
        ListElement {
            mainName: "Alphabet"
    
            subAlpha: [
                ListElement { alphaName: "A" },
                ListElement { alphaName: "B" }
            ]
        } } 
    

    How can I add element in inner list using javascript? In other words, how can I add element to subAlpha model?

    • muru
      muru over 8 years
      @clearkimura Programming questions related to the Ubuntu SDK (which uses QML) are on-topic.
    • Admin
      Admin over 8 years
      @muru I hardly noticed the qml tag, which was the only clue in the question earlier. So, I have edited the question using "QML" keyword to make it clearly on-topic.
  • Robert Schroll
    Robert Schroll over 8 years
    The question is about QML, not Javascript. Though QML does use Javascript for its procedural parts, its declarative language is not Javascript. The OP's code is perfectly valid QML; changing it to Javascript vastly changes its meaning.
  • Simon1901
    Simon1901 over 8 years
    thx @robert-schroll, I did't see that. My bad :(