Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

JavaScript Expressions in QML

 This article is a work-in-progress.

JavaScript adds logic to QML components. Properties can bind to JavaScript expressions or reside inline in functions or signal handlers. The QML engine will then interpret the expression to calculate new property values or to execute a routine.

The JavaScript runtime can run valid standard JavaScript constructs such as conditional operators, arrays, variable setting, 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. In QML you cannot add, 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 should be explicitly declared.

Adding Logic

The QML Elements provide a declarative way of creating and managing the interface layout and scene. Binding properties or signal handlers to JavaScript expressions adds logic to the QML application.

Suppose that a button represented by a Rectangle element has a MouseArea and a Text label. The MouseArea will call its onPressed handler when the user presses the defined interactive area. The QML engine will execute the contents bound to the onPressed and onReleased handlers. Typically, a signal handler is bound to JavaScript expressions to initiate other events or to simply assign property values.

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

     MouseArea {
         id: mousearea
         anchors.fill: parent

         onPressed: {
             label.text = "I am Pressed!"
         }
         onReleased: {
             label.text = "Click Me!"
         }

     }

     Text {
         id: label
         anchors.centerIn: parent
         text: "Press Me!"
     }
 }

During startup, the QML engine will set up and initialize the property bindings. The JavaScript conditional operator is a valid property binding.

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

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

     MouseArea {
         id: mousearea
         anchors.fill: parent
     }
 }

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.

 Item {
     function factorial(a) {
         a = parseInt(a);
         if (a <= 0)
             return 1;
         else
             return a * factorial(a - 1);
     }

     MouseArea {
         anchors.fill: parent
         onClicked: console.log(factorial(10))
     }
 }

The factorial function will run whenever the MouseArea detects a clicked signal.

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.

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:

 import "factorial.js" as MathFunctions
 Item {
     MouseArea {
         anchors.fill: parent
         onClicked: console.log(MathFunctions.factorial(10))
     }
 }

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

JavaScript Expressions

The JavaScript runtime run regular JavaScript expressions as defined by the

Variables and Properties

-variables -basic data types -values and assigning -relate to property binding

Conditional Loops

- for loops et al. - conditional operator

Data Structures

- arrays - object - relate to the content below about valid JS scope, objects, etc. - more advanced data types such as accessing QML list

Functions

- function declaration - function assignment (return values) - function parameters - connecting functions - importing libraries, functions - difference between JS functions and signals and QML methods

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:



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

See Connecting Signals to Methods and Signals for more information.

Advanced Usage

- using JS to access QML scene - using JS for algorithms - sorting, reordering lists - how to modify other QML entities with JS

Importing JavaScript into QML

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).

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().




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().

In QtQuick 2.0, support has been added to allow JavaScript files to import other JavaScript files and also QML modules using a variation of the standard QML import syntax (where all of the previously described rules and qualifications apply).

A JavaScript file may import another in the following fashion:

 .import "filename.js" as UniqueQualifier

For example:

 .import "factorial.js" as MathFunctions

A JavaScript file may import a QML module in the following fashion:

 .import Module.Name MajorVersion.MinorVersion as UniqueQualifier

For example:

 .import Qt.test 1.0 as JsQtTest

In particular, this may be useful in order to access functionality provided via a module API; see qmlRegisterModuleApi() for more information.

Due to the ability of a JavaScript file to import another script or QML module in this fashion in QtQuick 2.0, some extra semantics are defined:

  • a script with imports will not inherit imports from the QML file which imported it (so accessing Component.error will fail, for example)
  • a script without imports will inherit imports from the QML file which imported it (so accessing Component.error will succeed, for example)
  • a shared script (i.e., defined as .pragma library) does not inherit imports from any QML file even if it imports no other scripts

The first semantic is conceptually correct, given that a particular script might be imported by any number of QML files. The second semantic is retained for the purposes of backwards-compatibility. The third semantic remains unchanged from the current semantics for shared scripts, but is clarified here in respect to the newly possible case (where the script imports other scripts or modules).

Code-Behind Implementation Files

Most JavaScript files imported into a QML file are stateful 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.

 // factorial.js
 .pragma library

 function factorial(a) {
     a = parseInt(a);
     if (a <= 0)
         return 1;
     else
         return a * factorial(a - 1);
 }

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.

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:

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

     Component.onCompleted: startupFunction();
 }

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 the value returned by calling Qt.binding() where the parameter to Qt.binding() is a function that returns the required value.

See Property Assignment versus Property Binding for details.

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.

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

    It can be trivially modified to this legal code.

     var a = 1;
     for (var ii = 1; ii < 10; ++ii)
         a = a * ii;
     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.

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

    Global code that accesses QML objects will not run correctly.

     // Invalid global code - the "rootObject" variable is undefined
     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:

     Item {
         width: 200; height: 100
         function mouseAreaClicked(area) {
             console.log("Clicked in area at: " + area.x + ", " + area.y);
         }
         // This will not work because this is undefined
         MouseArea {
             height: 50; width: 200
             onClicked: mouseAreaClicked(this)
         }
         // This will pass area2 to the function
         MouseArea {
             id: area2
             y: 50; height: 50; width: 200
             onClicked: mouseAreaClicked(area2)
         }
     }

Scarce Resources in JavaScript

As described in the documentation for QML Basic Types, a var type property may hold a "scarce resource" (image or pixmap). There are several important semantics of scarce resources which should be noted:

  • By default, a scarce resource is automatically released by the declarative engine as soon as evaluation of the expression in which the scarce resource is allocated is complete if there are no other references to the resource
  • A client may explicitly preserve a scarce resource, which will ensure that the resource will not be released until all references to the resource are released and the JavaScript engine runs its garbage collector
  • A client may explicitly destroy a scarce resource, which will immediately release the resource

In most cases, allowing the engine to automatically release the resource is the correct choice. In some cases, however, this may result in an invalid variant being returned from a function in JavaScript, and in those cases it may be necessary for clients to manually preserve or destroy resources for themselves.

For the following examples, imagine that we have defined the following class:


and that we have registered it with the QML type-system as follows:


The AvatarExample class has a property which is a pixmap. When the property is accessed in JavaScript scope, a copy of the resource will be created and stored in a JavaScript object which can then be used within JavaScript. This copy will take up valuable system resources, and so by default the scarce resource copy in the JavaScript object will be released automatically by the declarative engine once evaluation of the JavaScript expression is complete, unless the client explicitly preserves it.

Example One: Automatic Release

In the following example, the scarce resource will be automatically released after the binding evaluation is complete.



Example Two: Automatic Release Prevented By Reference

In this example, the resource will not be automatically released after the binding expression evaluation is complete, because there is a property var referencing the scarce resource.



Example Three: Explicit Preservation

In this example, the resource must be explicitly preserved in order to prevent the declarative engine from automatically releasing the resource after evaluation of the imported script.



Example Four: Explicit Destruction

In the following example, we release (via destroy()) an explicitly preserved scarce resource variant. This example shows how a client may free system resources by releasing the scarce resource held in a JavaScript object, if required, during evaluation of a JavaScript expression.



Example Five: Explicit Destruction And JavaScript References

One thing to be aware of when using "var" type properties is that they hold references to JavaScript objects. As such, if multiple references to one scarce resource is held, and the client calls destroy() on one of those references (to explicitly release the scarce resource), all of the references will be affected.


Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 5.0-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web