How to add element for QML ListModel using Javascript?

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?

2

2 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like