Why is this 'keyValueList.push(KeyValue{})' code syntax incorrect in qml?
-
-
@mirro said in Why is this 'keyValueList.push(KeyValue{})' code syntax incorrect in qml?:
push(KeyValue{})
you can not create your qml object like that, see Dynamic QML Object Creation
Window { id: root visible: true width: 640 height: 480 property var keyValueList : [] onKeyValueListChanged:{ for(var i=0;i<keyValueList.length;i++){ console.log(keyValueList[i].color) //js kay-value //console.log(keyValueList[i].key) } } Component.onCompleted: { var tmp = [] // temporary list needed, can't keyValueList.push() directly for(var i=0;i<10;i++){ var newObject = Qt.createQmlObject('import QtQuick 2.15; Rectangle {color: "red";}',root); // Put your Type instead of rectangle tmp.push(newObject) } keyValueList = tmp } // js kay-value // Component.onCompleted:{ // var tmp = [] // for(var i=0;i<10;i++){ // tmp.push({key : Math.random()}) // } // keyValueList = tmp // } }
-
@LeLev Thank you. I just tested your method successfully
But I don't understand why you can't just assign values but use temporary variables instead?
Also, do I need to free memory in this 'Component.onDestruction'?Component.onCompleted: { var tmp = [] for(var i=0;i<10;i++){ var newObject = Qt.createQmlObject('import customqml 1.0;KeyValue{id:key}',root) tmp.push(newObject) } keyValueList = tmp }
-
@mirro said in Why is this 'keyValueList.push(KeyValue{})' code syntax incorrect in qml?:
But I don't understand why you can't just assign values but use temporary variables instead?
you can, but be aware of
https://doc.qt.io/qt-5/qml-variant.html#storing-arrays-and-objectsAdditionally, since items and attributes are not QML objects, changing the values they contain does not trigger property change notifications. If the above example had onItemsChanged or onAttributesChanged signal handlers, they would not be called when assigning individual entries in either property. If, however, the items or attributes properties themselves were reassigned to different values, then such handlers would be called.
@mirro said in Why is this 'keyValueList.push(KeyValue{})' code syntax incorrect in qml?:
Also, do I need to free memory in this 'Component.onDestruction'?
AFAIK no, because there is automatic garbage collection