Defining JavaScript Resources in QML¶
Description of how JavaScript files may be defined for use in QML
The program logic for a QML application may be defined in JavaScript. The JavaScript code may either be defined in-line in QML documents, or separated into JavaScript files (known as JavaScript Resources
in QML).
There are two different kinds of JavaScript resources which are supported in QML: code-behind implementation files, and shared (library) files. Both kinds of JavaScript resource may be imported by other JavaScript resources, or included in QML modules .
Code-Behind Implementation Resource¶
Most JavaScript files imported into a QML document are stateful implementations for the QML document importing them. In these cases, each instance of the QML object type defined in the document requires a separate copy of the JavaScript objects and state in order to behave correctly.
The default behavior when importing JavaScript files is to provide a unique, isolated copy for each QML component instance. If that JavaScript file does not import any resources or modules with a .import
statement, its code will run in the same scope as the QML component instance and consequently can access and manipulate the objects and properties declared in that QML component. Otherwise, it will have its own unique scope, and objects and properties of the QML component should be passed to the functions of the JavaScript file as parameters if they are required.
An example of a code-behind implementation resource follows:
// MyButton.qml import QtQuick 2.0 import "my_button_impl.js" as Logic // A new instance of this JavaScript resource // is loaded for each instance of Button.qml. Rectangle { id: rect width: 200 height: 100 color: "red" MouseArea { id: mousearea anchors.fill: parent onClicked: Logic.onClicked(rect) } }// my_button_impl.js var clickCount = 0; // this state is separate for each instance of MyButton function onClicked(button) { clickCount += 1; if ((clickCount % 5) == 0) { button.color = Qt.rgba(1,0,0,1); } else { button.color = Qt.rgba(0,1,0,1); } }
In general, simple logic should be defined in-line in the QML file, but more complex logic should be separated into code-behind implementation resources for maintainability and readability.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.