I am trying to create a map in a function in QML. I tried this:
var myMap= new Map()
var length = myArray.count
for (var i = 0; i < length; i++)
myMap.set(i, true)
It does not complain on the creation of the Map itself, but the set method. This is what the application outputs during run-time:
TypeError: Property 'set' of object is not a function
I used this as my reference for available methods of Map:
Map documentation
It looks like QML does not support calling the set method. I tried to find some documentation of what QML does and does not support, but could not find it. This makes it hard to know as I can not find out before after I have written and run the code.
Has anyone been able to use Map in QML and/or know where to find documentation about what Javascript functionality QML supports?
I guess you are misunderstanding what's the Map
object in QML.
I strongly suspect that's not what you expect it to be.
Instead, QML has automatic type conversion between QVariantMap
and JavaScript object.
This means that you should rely on plain JavaScript objects and their key-value model when you are working in a QML environment and want to create a map.
It's a matter of doing this:
var myMap= { };
var length = myArray.count;
for (var i = 0; i < length; i++)
myMap[i] = true;
This worked for me (Qt 5.14.2).
...
Label {
property var stateInfo: (new Map([
[MyCustomCPPType.State.Idle, "Idle"],
[MyCustomCPPType.State.Collecting, "Collecting"],
[MyCustomCPPType.State.Done, "Done"]
]))
text: stateInfo.get(MyCustomCPPTypeInstance.state)
}
...
I think that previous version of my answer was not correct.
As I understand all JS objects, properties and functions that can be used in QML are listed here. ECMA-262 specification stands only for the reference to the objects listed in the docs and nothing else. You will not be able to use Map
object correctly unfortunately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With