gpt4 book ai didi

qml - 无法将 qml 属性初始化为 {}

转载 作者:行者123 更新时间:2023-12-02 17:15:46 27 4
gpt4 key购买 nike

属性变体 a:{}似乎不起作用。 a 最终未定义,而不是一个空字典。

我对 Javascript 不是很有经验...初始化属性以保存字典的正确方法是什么?

以下 qml 在控制台上打印“qrc:/main.qml:13: TypeError: Type error”。但是,如果 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))
}
}

最佳答案

可以引用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 .

关于qml - 无法将 qml 属性初始化为 {},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627883/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com