jimav
jimav

Reputation: 838

Can not initialize qml property to {}

property variant a: {} does not seem to work. a ends up being undefined, rather than an empty dictionary.

I'm not very experienced with Javascript ... what is the correct way to initialize a property to hold an empty dictionary?

The following qml prints "qrc:/main.qml:13: TypeError: Type error" on the console. However, if a is initialized to, say {"dummyentry": 42}, then the expected results are logged.

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true; width: 600; height: 200

    property variant a: {}

    Component.onCompleted: {
        console.log("initial a="+JSON.stringify(a)) // TypeError: Type error
        a["newkey"] = 999  // gets "TypeError: Type error"
        console.log("updated a="+JSON.stringify(a))
    }
}

Upvotes: 3

Views: 4172

Answers (2)

Sergey Neimushchev
Sergey Neimushchev

Reputation: 76

You could refer to Qt documentation:

The QML syntax defines that curly braces on the right-hand-side of a property value initialization assignment denote a binding assignment. This can be confusing when initializing a var property, as empty curly braces in JavaScript can denote either an expression block or an empty object declaration. If you wish to initialize a var property to an empty object value, you should wrap the curly braces in parentheses.

Therefore, when using the property var a: {}, the curly braces were interpreted as an empty expression, whose result is undefined.

With using the property var a: ({}) syntax you will create an empty JS object. You can add to it both properties and methods, but with just a set of properties, it will work exactly like a dictionary.

You can access object properties in two ways:

objectName.propertyName
objectName["propertyName"]

Here you can find more information about JS objects: link.

Upvotes: 5

jimav
jimav

Reputation: 838

It must be a qml syntax issue. The work-around is to say

 property variant a: ( {} )

As noted in the question, it does work to say

 property variant a { "somekey": value }

...without parenthesis.

Does anyone know how qml is interpreting an unadorned '{}', and why it results in undefined?

Upvotes: 1

Related Questions