- 1. Example
- 2. Conclusion
In the framework of the project on QML there is an opportunity not only to connect JavaScript files in QML files, but also in other JavaScript files. The syntax for connecting these files will be similar to that used in QML files.
For example, a variant of connecting a JavaScript file in a QML file
import "first.js" as FirstJs
Then, how to connect a JavaScript file to another JavaScript file will differ only by the presence of a dot before this line
.import "first.js" as FirstJs
Example
We are given a small project, in which there are the following files
- main.qml
- first.js
- second.js
The next task is to connect first.js to main.qml and call a function from this JavaScript file, which will call the function from second.js , which will be connected in the file first.js .
main.qml
import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 import "first.js" as FirstJs // Connecting first.js ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Button { anchors.centerIn: parent text: qsTr("Click Me") // By clicking the button, we call the function from the first.js file onClicked: FirstJs.func() } }
second.js
This file has only a function for outputting the Second line to the console. This function will need to be called in the first.js file.
.pragma library function func() { console.log("Second") }
first.js
.pragma library .import "second.js" as Second // Connecting second.js function func() { console.log("First") Second.func() // Calling a function from file second.js }
Conclusion
As a result, when the button is pressed, the function from the file first.js will be called, which will output its message to the console and call the function from file second.js .
The following message will be displayed in the console:
qml: First qml: Second