QML 中的结构化常量
Structured constants in QML
根据其他帖子(跨站点),我创建了一个 Constants.qml 文件,其中包含:
pragma Singleton
import QtQuick 2.6
QtObject {
readonly property alias MyConst: myConst_
QtObject
{
id: myConst_
readonly property int Test: 1
readonly property int Apple: 2
readonly property int Dog: 4
}
}
在其他地方,我试图像这样引用这些值:
var a = Constants.MyConst.Test
产生错误:
TypeError: Cannot read property 'Test' of undefined
有人可以解释一下如何进行这项工作吗?
试试小写:
pragma Singleton
import QtQuick 2.6
QtObject {
readonly property alias myConst: myConst_
QtObject
{
id: myConst_
readonly property int test: 1
readonly property int apple: 2
readonly property int dog: 4
}
}
有时候把所有的常量放到一个单独的JS文件中会很方便,例如:
// cosntants.js
.pragma library
var TEST = 1
var Apple = "x"
var dOg = 3.14
并在 QML 中使用它,例如:
// main.qml
import "cosntants.js" as JS
...
var a = JS.TEST + JS.Apple
当然你可以让它们结构化,为此只需使用普通的 JS 对象。您可以查看我的 project 以获取更多示例。
我遇到了完全相同的问题,在我的情况下,解决方案是在与 Constants.qml 文件相同的文件夹中添加一个名为 qmldir 的文件,其内容为:
singleton Constants Constants.qml
根据其他帖子(跨站点),我创建了一个 Constants.qml 文件,其中包含:
pragma Singleton
import QtQuick 2.6
QtObject {
readonly property alias MyConst: myConst_
QtObject
{
id: myConst_
readonly property int Test: 1
readonly property int Apple: 2
readonly property int Dog: 4
}
}
在其他地方,我试图像这样引用这些值:
var a = Constants.MyConst.Test
产生错误:
TypeError: Cannot read property 'Test' of undefined
有人可以解释一下如何进行这项工作吗?
试试小写:
pragma Singleton
import QtQuick 2.6
QtObject {
readonly property alias myConst: myConst_
QtObject
{
id: myConst_
readonly property int test: 1
readonly property int apple: 2
readonly property int dog: 4
}
}
有时候把所有的常量放到一个单独的JS文件中会很方便,例如:
// cosntants.js
.pragma library
var TEST = 1
var Apple = "x"
var dOg = 3.14
并在 QML 中使用它,例如:
// main.qml
import "cosntants.js" as JS
...
var a = JS.TEST + JS.Apple
当然你可以让它们结构化,为此只需使用普通的 JS 对象。您可以查看我的 project 以获取更多示例。
我遇到了完全相同的问题,在我的情况下,解决方案是在与 Constants.qml 文件相同的文件夹中添加一个名为 qmldir 的文件,其内容为:
singleton Constants Constants.qml