- Simple QML Module usage in QML file
- Singleton QML Module usage in QML file
- QML file in JS file
- JS file usage in QML file
- JS file usage in JS file
Structure
-- Use.qml
-- FOLDER
---- Module
------ qmldir
------ Module.qml
Module.qml
QtObject {
property string foo: 'bar'
}
qmldir
MyModule 1.0 Module.qml
Use.qml
import FOLDER.Module 1.0
QtObject {
MyModule {
id: myInitializedModule
}
Component.onCompleted: console.log(myInitializedModule.foo)
}
There is need to initialize module
... MyModule { id: myInitializedModule } ...
Structure
-- Use.qml
-- FOLDER
---- Module
------ qmldir
------ Module.qml
Module.qml
pragma Singleton
QtObject {
property string foo: 'bar'
}
qmldir
singleton MyModule 1.0 Module.qml
Use.qml
import FOLDER.Module 1.0
QtObject {
Component.onCompleted: console.log(MyModule.foo)
}
- To make module a singleton use
pragma singleton
at start of file and the wordsingleton
inqmldir
before identifier- There is no need to initialize module, simply use the identifier used in
qmldir
file (MyModule
)
There is a way to do it, but I didn't succeed making it work.
Structure
-- Use.qml
-- animal.js
-- FOLDER
---- Module
------ qmldir
------ human.js
------ robot.js
animal.js
function AnimalConstructor(name) {
this.name = name;
}
human.js
.pragma library
function HumanConstructor(name) {
this.name = name;
}
robot.js
function RobotConstructor(name) {
this.name = name;
}
qmldir
Human 1.0 human.js
Robot 1.0 robot.js
Use.qml
import FOLDER.Module 1.0
import "animal.js" as Animal
QtObject {
property var human: new Human.HumanConstructor('vaska')
property var robot: new Robot.RobotConstructor('r2d2')
property var animal: new Animal.AnimalConstructor('petka')
Component.onCompleted: console.log(human.name, robot.name, animal.name)
}
- To make js file a library — put
.pragma library
at start of it- It is no difference between importing
library
and simple js file. The difference is thatlibrary
file will share its context between any file, that will import it- Js file names should start with lower case (
human.js
, notHuman.js
)- File content will be able by
Human
identifier used inqmldir
, so to use functions from file you should useHuman.HumanConstructor
- When importing js file by
import "path/to/file.js"
you have to use qualifier (as
)
Structure
-- FOLDER
---- Module
------ human.js
------ hand.js
------ foot.js
human.js
.import "hand.js" as Hand
Qt.include('foot.js');
function HumanConstructor(name) {
this.name = name;
this.hand = new Hand.HandConstructor();
this.foot = new FootConstructor();
}
hand.js
function HandConstructor() {}
HandConstructor.prototype.take = function() {...}
foot.js
function FootConstructor() {}
FootConstructor.prototype.kick = function() {...}
- When use
.import
you have to use a qualifier (as
).import
imports all the variables defined in the fileQt.include
imports only functions, but qualifier is not needed