4
votes

Is there any way to check existence and access a dynamically created object in QML/javascript (without using C++)?

I'm trying to create an application with an interface similar to a map - given an key and a object, my application must locate if an object with the key exists and overwrite with the new object. If it doesn't, the app must create a new object and associate with the key.

The documentation says that dynamically managed objects doesn't have IDs, and the only way I found to access them was by using objectName, which seems to require C++ application.

thanks in advance.

1

1 Answers

4
votes

You can use JavaScript object as a map. You can't directly manipulate it in QML, but you can move all code to handle this object into JavaScript file and include it as a module. Here is a simple example:

Map.js:

var _map = new Object()

function value(key) {
    return _map[key]
}

function setValue(key, value) {
    _map[key] = value
}

function remove(key) {
    delete _map[key]
}

function keys() {
    return Object.keys(_map)
}

function process() {
    for (var key in _map) {
        /* do something */
    }
}

QML example:

import QtQuick 1.1
import "Map.js" as Map

Item {
    Component.onCompleted: {
        Map.setValue("test", "hello")
        console.log("test = ", Map.value("test"))
        Map.remove("test", "hello")
        console.log("test = ", Map.value("test"))
    }
}

The output will be:

test =  hello
test =  undefined