- Qt 6.12
- Qt Qml
- The QML Reference
- Integrating QML and JavaScript
- JavaScript Expressions in QML Documents
- Qt 6.12.0 Reference Documentation

JavaScript in QML ◦ Dynamic QML Object Creation from JavaScript

# JavaScript Expressions in QML Documents

The JavaScript Host Environment provided by QML can run valid standard JavaScript constructs such as conditional operators, arrays, variable setting, and loops. In addition to the standard JavaScript properties, the QML Global Object includes a number of helper methods that simplify building UIs and interacting with the QML environment.

The JavaScript environment provided by QML is stricter than that in a web browser. For example, in QML you cannot add to, or modify, members of the JavaScript global object. In regular JavaScript, it is possible to do this accidentally by using a variable without declaring it. In QML this will throw an exception, so all local variables must be explicitly declared. See JavaScript Environment Restrictions for a complete description of the restrictions on JavaScript code executed from QML.

Various parts of QML documents can contain JavaScript code:

1. The body of property bindings. These JavaScript expressions describe relationships between QML object properties. When dependencies of a property change, the property is automatically updated too, according to the specified relationship.
2. The body of Signal handlers. These JavaScript statements are automatically evaluated whenever a QML object emits the associated signal.
3. The definition of custom methods. JavaScript functions that are defined within the body of a QML object become methods of that object.
4. Standalone JavaScript resource (.js) files. These files are actually separate from QML documents, but they can be imported into QML documents. Functions and variables that are defined within the imported files can be used in property bindings, signal handlers, and custom methods.

## JavaScript in property bindings

In the following example, the `color` property of Rectangle depends on the `pressed` property of TapHandler. This relationship is described using a conditional expression:

     import QtQuick 2.12

     Rectangle {
         id: colorbutton
         width: 200; height: 80;

         color: inputHandler.pressed ? "steelblue" : "lightsteelblue"

         TapHandler {
             id: inputHandler
         }
     }

In fact, any JavaScript expression (no matter how complex) may be used in a property binding definition, as long as the result of the expression is a value whose type can be assigned to the property. This includes side effects. However, complex bindings and side effects are discouraged because they can reduce the performance, readability, and maintainability of the code.

There are two ways to define a property binding: the most common one is shown in the example earlier, in a property initialization. The second (and much rarer) way is to assign the property a function returned from the Qt.binding() function, from within imperative JavaScript code, as shown below:

     import QtQuick 2.12

     Rectangle {
         id: colorbutton
         width: 200; height: 80;

         color: "red"

         TapHandler {
             id: inputHandler
         }

         Component.onCompleted: {
             color = Qt.binding(function() { return inputHandler.pressed ? "steelblue" : "lightsteelblue" });
         }
     }

See the property bindings documentation for more information about how to define property bindings, and see the documentation about Property Assignment versus Property Binding for information about how bindings differ from value assignments.

## JavaScript in signal handlers

QML object types can emit signals in reaction to certain events occurring. Those signals can be handled by signal handler functions, which can be defined by clients to implement custom program logic.

Suppose that a button represented by a Rectangle type has a TapHandler and a Text label. The TapHandler emits its tapped signal when the user presses the button. The clients can react to the signal in the `onTapped` handler using JavaScript expressions. The QML engine executes these JavaScript expressions defined in the handler as required. Typically, a signal handler is bound to JavaScript expressions to initiate other events or to assign property values.

     import QtQuick 2.12

     Rectangle {
         id: button
         width: 200; height: 80; color: "lightsteelblue"

         TapHandler {
             id: inputHandler
             onTapped: {
                 // arbitrary JavaScript expression
                 console.log("Tapped!")
             }
         }

         Text {
             id: label
             anchors.centerIn: parent
             text: inputHandler.pressed ? "Pressed!" : "Press here!"
         }
     }

For more details about signals and signal handlers, refer to the following topics:

- Signal and Handler Event System
- QML Object Attributes

## JavaScript in standalone functions

Program logic can also be defined in JavaScript functions. These functions can be defined inline in QML documents (as custom methods) or externally in imported JavaScript files.

### JavaScript in custom methods

Custom methods can be defined in QML documents and may be called from signal handlers, property bindings, or functions in other QML objects. Such methods are often referred to as inline JavaScript functions because their implementation is included in the QML object type definition (QML document), instead of in an external JavaScript file.

An example of an inline custom method is as follows:

     import QtQuick 2.12

     Item {
         function fibonacci(n){
             var arr = [0, 1];
             for (var i = 2; i < n + 1; i++)
                 arr.push(arr[i - 2] + arr[i -1]);

             return arr;
         }
         TapHandler {
             onTapped: console.log(fibonacci(10))
         }
     }

The fibonacci function is run whenever the TapHandler emits a `tapped` signal.

Note: The custom methods defined inline in a QML document are exposed to other objects, and therefore inline functions on the root object in a QML component can be invoked by callers outside the component. If this is not desired, the method can be added to a non-root object or, preferably, written in an external JavaScript file.

See the QML Object Attributes documentation for more information on defining custom methods in QML using JavaScript.

### Functions defined in a JavaScript file

Non-trivial program logic is best separated into a separate JavaScript file. This file can be imported into QML using an `import` statement, like the QML modules.

For example, the `fibonacci()` method in the earlier example could be moved into an external file named `fib.js`, and accessed like this:

     import QtQuick 2.12
     import "fib.js" as MathFunctions

     Item {
         TapHandler {
             onTapped: console.log(MathFunctions.fibonacci(10))
         }
     }

For more information about loading external JavaScript files into QML, read the section about Importing JavaScript Resources in QML.

### Connecting signals to JavaScript functions

QML object types that emit signals also provide default signal handlers for their signals, as described in the previous section. Sometimes, however, a client wants to trigger a function defined in a QML object when another QML object emits a signal. Such scenarios can be handled by a signal connection.

A signal emitted by a QML object may be connected to a JavaScript function by calling the signal's `connect()` method and passing the JavaScript function as an argument. For example, the following code connects the TapHandler's `tapped` signal to the `jsFunction()` in `script.js`:

     import QtQuick
     import "script.js" as MyScript

     Item {
         id: item
         width: 200; height: 200

         TapHandler {
             id: inputHandler
         }

         Component.onCompleted: {
             inputHandler.tapped.connect(MyScript.jsFunction)
         }
     }
     // script.js

     function jsFunction() {
         console.log("Called JavaScript function!")
     }

The `jsFunction()` is called whenever the TapHandler's `tapped` signal is emitted.

See Connecting Signals to Methods and Signals for more information.

## JavaScript in application startup code

It is occasionally necessary to run some imperative code at application (or component instance) startup. While it is tempting to just include the startup script as global code in an external script file, this can have severe limitations as the QML environment may not have been fully established. For example, some objects might not have been created or some property bindings may not have been established. See JavaScript Environment Restrictions for the exact limitations of global script code.

A QML object emits the `Component.completed` attached signal when its instantiation is complete. The JavaScript code in the corresponding `Component.onCompleted` handler runs after the object is instantiated. Thus, the best place to write application startup code is in the `Component.onCompleted` handler of the top-level object, because this object emits `Component.completed` when the QML environment is fully established.

For example:

     import QtQuick 2.0

     Rectangle {
         function startupFunction() {
             // ... startup code
         }

         Component.onCompleted: startupFunction();
     }

Any object in a QML file - including nested objects and nested QML component instances - can use this attached property. If there is more than one `onCompleted()` handler to execute at startup, they are run sequentially in an undefined order.

Likewise, every `Component` emits a destruction() signal just before being destroyed.

JavaScript in QML ◦ Dynamic QML Object Creation from JavaScript