1

I've found an issue tonight and I wonder if this is a mistake between the keyboard and the screen or a QML/javascript integration problem.

Here is my example:

var myHash = {}

for (var i=0; i<3; ++i) {
    var newObject = Qt.createQmlObject('import QtQuick 2.3; Rectangle {color: "red"; width: 20; height: 40}', main, "test")
    console.log(newObject.color)
    myHash[newObject] = i
}

for (var key in myHash) {
    console.log("Object type:" + key)
    console.log("Color: " + key.color)
}

The output is:

qml: Initial color: #ff0000
qml: Initial color: #ff0000
qml: Initial color: #ff0000
qml: Object type:QQuickRectangle(0x98e9ac8)
qml: Color: undefined
qml: Object type:QQuickRectangle(0x98da7a0)
qml: Color: undefined
qml: Object type:QQuickRectangle(0x970b328)
qml: Color: undefined

Thus, when I've stored my QML object in the hash-map myHash as a key, QML has kept the object type, but forgot the properties?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
jaddawyn
  • 351
  • 3
  • 8

1 Answers1

0

The issue is that JavaScript objects are most closely akin to a Map[String, Any] - so you aren't storing the object newObject as a key in myHash but rather the result of calling toValue / toString on newObject.

The solution is to store newObject as a value and use something else for the key:

var myHash = {}

for (var i=0; i<3; ++i) {
    var newObject = Qt.createQmlObject('import QtQuick 2.3; Rectangle {color: "red"; width: 20; height: 40}', main, "test")
    console.log(newObject.color)
    myHash["key_" + i] = newObject;
}

for (var key in myHash) {
    console.log("Object entry:" + key)
    console.log("Color: " + myHash[key].color)
}
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • This is not the good solution because: - I really want my qml object to be stored into my hash as a key, - By storing keys in this way, that will be really hard to retrieve my integer from my string key. – jaddawyn Nov 10 '14 at 22:56
  • 2
    @jaddawyn Why do you want to store it as the key? Your example looks like a flawed design--maybe it is maybe it isn't give us some explaination. Secondly: that's just not how it works, this might help: http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent – Daniel B. Chapman Nov 10 '14 at 23:02
  • I don't see any design problem, I just want to associate two QML objects (the code above is just done to highlight my question). But your link makes me understand javascript is only capable to store strings as a key. I was expecting better. Anyway thank you for the answers. – jaddawyn Nov 10 '14 at 23:09