How can javascript in a separate .js file access a QML singleton?
My javascript library wants to read configuration values stored in a singleton which is defined in TrConfig.qml:
// TrConfig.qml
pragma Singleton
import QtQml 2.0
QtObject {
property var myWidth: 234
}
The qmldir file contains
singleton TrConfig 1.0 TrConfig.qml
This works fine from inside .qml files by simply referencing TrConfig.<fieldname>. But in .js files after .import TrConfig as TC, referencing TC.<fieldname> always returns undefined.
// myjslib.js
.import QtQml 2.11 as QtQml
.import TrConfig as TC
function myfunc() {
console.log("In myjslib.js myWidth is " + TC.myWidth);
// prints "... myWidth is undefined"
}
Here is the main .qml file (run with "qml Foo.qml"):
// Foo.qml
import QtQuick
import QtQuick.Controls
import "myjslib.js" as J
Rectangle {
width: TrConfig.myWidth // this works
height: 100
color: "red"
Component.onCompleted: {
console.log("Foo onCompleted: myWidth="+TrConfig.myWidth);
J.myfunc();
}
}
The output is:
qml: Foo onCompleted: myWidth=234
qml: In myjslib.js myWidth is undefined
Any help would be greatly appreciated!
[Updated 11/6/21 to add ".import TrConfig as TC" into the .js file]