Ubuntu – How to add element for QML ListModel using Javascript

qmlqt

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?

Best Answer

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"})
    }
}