Trying to store javascript array as a QML property
-
For example, I have this QML object:
@Item {
id: something
}@I just wanna store a javascript array "abcArray" as QML property, just to make it usable in other functions and other QML objects.
So I tried doing this@Item {
id: something
property variant abcArray: Array()//A demo function
function demo() {
abcArray.push("I want to push this!!!");
abcArray.push("Please, please appear in the array!");
abcArray.push("crazy!");
//print out the length of the array
console.log(abcArray.length);
//Oh damn! it just outputs "0" all the time even if I pushed many things to it
}
}@In the end, it doesn't work, after all, the abcArray is still completely empty.
How to make it work? -
You can use ListModel to do that.
-
[quote author="leafaku" date="1331299888"]You can use ListModel to do that.[/quote]
But it would be too much for this simple thing, and it's a waste of memory! I just need to have an array of strings and no more. I don't need the "dict" thing of ListModel. -
You can use a javascript function that returns an array in the property
//in js file:
var arr{}Function Array() {
...
Return arr
} -
@Item {
id: something
property variant abcArrayComponent.onCompleted: {
abcArray = demo();
console.log(abcArray.length,abcArray);
}
//A demo function
function demo() {
var tmp = []
tmp.push("I want to push this!!!");
tmp.push("Please, please appear in the array!");
tmp.push("crazy!");
return tmp;
}
}@ -
I spend ages trying to work this out and finally discovered what none of the other threads say: there is now a "var" property which can contain any javascript object. For example:
property var myArray = []
-
thank you Damian
-
There are docs, you know ;-) Although I agree that they've been made hideously difficult to navigate now, since 5.0 times, for some reason.
See
http://doc-snapshot.qt-project.org/qt5-stable/qmlreference.html
and
http://doc-snapshot.qt-project.org/qt5-stable/qtqml-typesystem-topic.html
for more information.Cheers,
Chris. -
Thanks all.This definitely useful tips.
-
404 - Page Not Found.
-