I defined this javascript function that creates a component and checks, whether it is ready, in one of my QML files:
Item {
id: lib
function createCmpt(path) {
var cmpt = Qt.createComponent(path)
if (cmpt.status !== Component.Ready) {
if (cmpt.status === Component.Error) {
console.error("Error: " + cmpt.errorString())
}
console.error("Error: component not ready, path: " + path)
return null
}
return cmpt
}
...
}
Now, I would like to use this function in any of my .qml files (global usage). I know that I can declare this function at the root of my app (ApplicationWindow in my case). But is there a way to define this function maybe in a separate javascript file?
I tried to do that like this (qml.js):
.pragma library
function createCmpt(path) {
var cmpt = Qt.createComponent(path)
if (cmpt.status !== Component.Ready) {
if (cmpt.status === Component.Error) {
console.error("Error: " + cmpt.errorString())
}
console.error("Error: component not ready, path: " + path)
return null
}
return cmpt
}
But of course this does not work, as this seems to be vanilla javascript, which has no knowledge of the global Qt object.
Any ideas, on how I could define this function in my external js file?
UPDATE: I did not read my error message carefully enough! It seems like the global Qt object is indeed known to the javascript. However, Component was not. In the official doc I found a way to import qml namespaces to javascript files and I rewrote my code to:
.pragma library
.import QtQml 2.11 as QtQml
function createCmpt(path) {
var cmpt = Qt.createComponent(path)
if (cmpt.status !== QtQml.Component.Ready) {
if (cmpt.status === QtQml.Component.Error) {
console.error("Error: " + cmpt.errorString())
}
console.error("Error: component not ready, path: " + path)
return null
}
return cmpt
}
However, now I get an error:
QObject::startTimer: Timers cannot be started from another thread
I am not sure what to do with it