Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it not possible to create a map datatype in QML?

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?

like image 780
uniquenamehere Avatar asked Jun 02 '16 18:06

uniquenamehere


3 Answers

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;
like image 143
skypjack Avatar answered Nov 18 '22 22:11

skypjack


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)
}
...
like image 42
marsl Avatar answered Nov 18 '22 23:11

marsl


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.

like image 1
Filip Hazubski Avatar answered Nov 19 '22 00:11

Filip Hazubski