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?
22 Answers
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"}) }
} To make it valid JSON/Javascript
a = { id: mainModel, ListElement: { mainName: "Alphabet", subAlpha: [ { alphaName: "A" }, { alphaName: "B" } ] }
} and then add to subAlpha
a.ListElement.subAlpha.push({ alphaName: "C" }) 2