Integrating JavaScript

QML encourages building UIs declaratively, using Property Binding and the composition of existing QML Elements. To allow the implementation of more advanced behavior, QML integrates tightly with imperative JavaScript code.

The JavaScript environment provided by QML is stricter than that in a web browser. In QML you cannot add, or modify, members of the JavaScript global object. 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 should be explicitly declared.

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.

Inline JavaScript

Small JavaScript functions can be written inline with other QML declarations. These inline functions are added as methods to the QML element that contains them.

  1. Item  {
  2.     function factorial(a)  {
  3.         a = parseInt(a);
  4.         if (a <= 0)
  5.             return 1;
  6.         else
  7.             return a * factorial(a - 1);
  8.     }
  10.     MouseArea  {
  11.         anchors.fill: parent
  12.         onClicked: console.log(factorial(10))
  13.     }
  14. }

As methods, inline functions on the root element 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 element or, preferably, written in an external JavaScript file.

Separate JavaScript files

Large blocks of JavaScript should be written in separate files. These files can be imported into QML files using an import statement, in the same way that modules are imported.

For example, the factorial() method in the above example for Inline JavaScript could be moved into an external file named factorial.js, and accessed like this:

  1. import "factorial.js" as MathFunctions
  2. Item  {
  3.     MouseArea  {
  4.         anchors.fill: parent
  5.         onClicked: console.log(MathFunctions.factorial(10))
  6.     }
  7. }

Both relative and absolute JavaScript URLs can be imported. In the case of a relative URL, the location is resolved relative to the location of the QML Document that contains the import. If the script file is not accessible, an error will occur. If the JavaScript needs to be fetched from a network resource, the component's status is set to "Loading" until the script has been downloaded.

Imported JavaScript files are always qualified using the "as" keyword. The qualifier for JavaScript files must be unique, so there is always a one-to-one mapping between qualifiers and JavaScript files. (This also means qualifiers cannot be named the same as built-in JavaScript objects such as Date and Math).

Code-Behind Implementation Files

Most JavaScript files imported into a QML file are stateful, logic implementations for the QML file importing them. In these cases, for QML component instances to behave correctly each instance requires a separate copy of the JavaScript objects and state.

The default behavior when importing JavaScript files is to provide a unique, isolated copy for each QML component instance. The code runs in the same scope as the QML component instance and consequently can can access and manipulate the objects and properties declared.

Stateless JavaScript libraries

Some JavaScript files act more like libraries - they provide a set of stateless helper functions that take input and compute output, but never manipulate QML component instances directly.

As it would be wasteful for each QML component instance to have a unique copy of these libraries, the JavaScript programmer can indicate a particular file is a stateless library through the use of a pragma, as shown in the following example.

  1. // factorial.js
  2. .pragma library
  4. function factorial(a)  {
  5.     a = parseInt(a);
  6.     if (a <= 0)
  7.         return 1;
  8.     else
  9.         return a * factorial(a - 1);
  10. }

The pragma declaration must appear before any JavaScript code excluding comments.

As they are shared, stateless library files cannot access QML component instance objects or properties directly, although QML values can be passed as function parameters.

Importing One JavaScript File From Another

If a JavaScript file needs to use functions defined inside another JavaScript file, the other file can be imported using the Qt.include() function. This imports all functions from the other file into the current file's namespace.

For example, the QML code below left calls showCalculations() in script.js, which in turn can call factorial() in factorial.js, as it has included factorial.js using Qt.include().

  1. import QtQuick 1.0
  2. import "script.js" as MyScript
  4. Item  {
  5.     width: 100; height: 100
  7.     MouseArea  {
  8.         anchors.fill: parent
  9.         onClicked:  {
  10.             MyScript.showCalculations(10)
  11.             console.log("Call factorial() from QML:",
  12.                 MyScript.factorial(10))
  13.         }
  14.     }
  15. }

Notice that calling Qt.include() imports all functions from factorial.js into the MyScript namespace, which means the QML component can also access factorial() directly as MyScript.factorial().

Running JavaScript at Startup

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 run. QML JavaScript Restrictions covers the exact limitations of global script code.

The QML Component element provides an attached onCompleted property that can be used to trigger the execution of script code at startup after the QML environment has been completely established. For example:

  1. Rectangle  {
  2.     function startupFunction()  {
  3.         // ... startup code
  4.     }
  6.     Component.onCompleted: startupFunction();
  7. }

Any element in a QML file - including nested elements 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, the Component::onDestruction attached property is triggered on component destruction.

JavaScript and Property Binding

Property bindings can be created in JavaScript by assigning the property with a function that returns the required value.

See Property Assignment versus Property Binding for details.

Receiving QML Signals in JavaScript

To receive a QML signal, use the signal's connect() method to connect it to a JavaScript function.

For example, the following code connects the MouseArea clicked signal to the jsFunction() in script.js:

  1. import QtQuick 1.0
  2. import "script.js" as MyScript
  4. Item  {
  5.     id: item
  6.     width: 200; height: 200
  8.     MouseArea  {
  9.         id: mouseArea
  10.         anchors.fill: parent
  11.     }
  13.     Component.onCompleted:  {
  14.         mouseArea.clicked.connect(MyScript.jsFunction)
  15.     }
  16. }

The jsFunction() will now be called whenever MouseArea's clicked signal is emitted.

See Connecting Signals to Methods and Signals for more information.

QML JavaScript Restrictions

QML executes standard JavaScript code, with the following restrictions:

  • JavaScript code cannot modify the global object.

    In QML, the global object is constant - existing properties cannot be modified or deleted, and no new properties may be created.

    Most JavaScript programs do not intentionally modify the global object. However, JavaScript's automatic creation of undeclared variables is an implicit modification of the global object, and is prohibited in QML.

    Assuming that the a variable does not exist in the scope chain, the following code is illegal in QML.

    1. // Illegal modification of undeclared variable
    2. a = 1;
    3. for (var ii = 1; ii < 10; ++ii)
    4.     a = a * ii;
    5. console.log("Result: " + a);

    It can be trivially modified to this legal code.

    1. var a = 1;
    2. for (var ii = 1; ii < 10; ++ii)
    3.     a = a * ii;
    4. console.log("Result: " + a);

    Any attempt to modify the global object - either implicitly or explicitly - will cause an exception. If uncaught, this will result in an warning being printed, that includes the file and line number of the offending code.

  • Global code is run in a reduced scope

    During startup, if a QML file includes an external JavaScript file with "global" code, it is executed in a scope that contains only the external file itself and the global object. That is, it will not have access to the QML objects and properties it normally would.

    Global code that only accesses script local variable is permitted. This is an example of valid global code.

    1. var colors = [ "red", "blue", "green", "orange", "purple" ];

    Global code that accesses QML objects will not run correctly.

    1. // Invalid global code - the "rootObject" variable is undefined
    2. var initialPosition =  { rootObject.x, rootObject.y }

    This restriction exists as the QML environment is not yet fully established. To run code after the environment setup has completed, refer to Running JavaScript at Startup.

  • The value of this is currently undefined in QML in the majority of contexts

    The this keyword is supported when binding properties from JavaScript. In all other situations, the value of this is undefined in QML.

    To refer to any element, provide an id. For example:

    1.                         Item  {
    2.     width: 200; height: 100
    3.     function mouseAreaClicked(area)  {
    4.         console.log("Clicked in area at: " + area.x + ", " + area.y);
    5.     }
    6.     // This will not work because this is undefined
    7.     MouseArea  {
    8.         height: 50; width: 200
    9.         onClicked: mouseAreaClicked(this)
    10.     }
    11.     // This will pass area2 to the function
    12.     MouseArea  {
    13.         id: area2
    14.         y: 50; height: 50; width: 200
    15.         onClicked: mouseAreaClicked(area2)
    16.     }
    17. }
Notes provided by the Qt Community

No notes