qtqmlqtquick2dynamicobject

Create component dynmically in QML (ListElement in ListModel)


I want to create members of an QML-ListModel dynamically. Static creation is no problem and works fine:

 ListModel{
            id: sList 

            ListElement{
                url: "Res/ex1.jpg"
                time: 10
            }

            ListElement{
                url: "Res/ex2.jpg"
                time: 10
            }
        }

I chosse QML function Qt.createQmlObject, sList was already create at startup:

Qt.createQmlObject("import QtQuick 2.5; ListElement{url: \"Res/ex1.jpg\"; time: 10; }", sList, "dynamicItem");

I finally got an error:

file:///C:[...]TEP46Py6_2/main.qml:156: Error: Qt.createQmlObject(): failed to create object: 
file:///C:[...]TEP46Py6_2/dynamicItem:1:53: Cannot assign to non-existent property "time"

Yes, ListElement hasn't a native property time (and also url), but ListElement commonly has no native properties. Could anybody give me an advice? Thank you.


Solution

  • You just have to use the append function:

    sList.append({"url": "Res/ex1.jpg", "time": 10})