Dynamically create QML ListElement and content

So, I'm trying to dynamically create ListElements in a ListModel . This works fine until I try to write some content in the loadable ListElements element dynamically.

I tried to create my own file with the ListElement inside and the hour as a property, but then the model had an error saying that ListElements could not be nested.

Error starting code below:

Cannot assign non-existent hour property

How can i solve this?

Code:

 import QtQuick 2.0 ListModel { id: listModel Component.onCompleted: { for (var i = 0; i < 24; i++) { var object = createListElement(listModel) } } function createListElement(parent) { var object = Qt.createQmlObject('import QtQuick 2.0; ListElement { hour: "01" }', parent); return object; } } 

EDIT: Change the line of code in the function to:

 var object = Qt.createQmlObject('import QtQuick 2.0; ListElement { property string hour: "23" }', parent); 

Now I get no errors, but the items are still not showing in the list.

DECISION:

 import QtQuick 2.0 ListModel { id: listModel Component.onCompleted: { for (var i = 0; i < 24; i++) { append( { hour: i.toString() } ) } } } 
+6
source share
1 answer

I'm not sure why this does not work, but using simple old JavaScript objects, the following is done:

 import QtQuick 2.4 import QtQuick.Window 2.0 Window { width: 400 height: 400 ListView { id: listView anchors.fill: parent model: listModel delegate: Rectangle { width: listView.width height: listView.height / 4 Text { text: hour anchors.centerIn: parent } } } ListModel { id: listModel Component.onCompleted: { for (var i = 0; i < 24; i++) { append(createListElement()); } } function createListElement() { return { hour: "01" }; } } } 
+7
source

Source: https://habr.com/ru/post/980867/


All Articles