2017-10-08 66 views
1

property variant a: {} 似乎并没有工作。 a最终未定义,而不是空字典。无法初始化QML属性{}

我不是非常有经验的JavaScript ...什么是初始化属性,以持有字典正确的方法是什么?

以下QML打印 “QRC:/main.qml:13:类型错误:类型错误” 在控制台上。但是,如果a初始化为{"dummyentry": 42},然后 ,则会记录预期结果。

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)) 
    } 
} 
+1

此行为全部在文档http://doc.qt.io/qt-5/qml-var.html中阐述。对于行为的*推理*对我来说不太清楚。 –

回答

0

它必须是qml语法问题。的解决办法是说

property variant a: ({}) 

如问题指出,它工作说

property variant a { "somekey": value } 

...没有括号。

有谁知道QML是如何解释的朴实“{}”,为什么它会导致undefined

2

您可以参考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.

因此,在使用时property var a: {},花括号中解释为空表达式,其结果是不确定的。

随着使用property var a: ({})语法,你将创建一个空的JS对象。你可以添加它的属性和方法,但只有一组属性,它会像字典一样工作。

您可以通过两种方式访问​​对象属性:

objectName.propertyName 
objectName["propertyName"] 

在这里你可以找到关于JS对象的详细信息:link