Home · All Classes · All Functions · Overviews

QML Global Object

Contains all the properties of the JavaScript global object, plus:

Qt Object

The Qt object provides useful enums and functions from Qt, for use in all QML files.

Enums

The Qt object contains all enums in the Qt namespace. For example, you can access the AlignLeft member of the Qt::AlignmentFlag enum with Qt.AlignLeft.

For a full list of enums, see the Qt Namespace documentation.

Types

The Qt object also contains helper functions for creating objects of specific data types. This is primarily useful when setting the properties of an item when the property has one of the following types:

There are also string based constructors for these types, see Qml Types.

Qt.rgba(qreal red, qreal green, qreal blue, qreal alpha)

This function returns a Color with the specified red, green, blue and alpha components. All components should be in the range 0-1 inclusive.

Qt.hsla(qreal hue, qreal saturation, qreal lightness, qreal alpha)

This function returns a Color with the specified hue, saturation, lightness and alpha components. All components should be in the range 0-1 inclusive.

Qt.rect(int x, int y, int width, int height)

This function returns a Rect with the top-left corner at x, y and the specified width and height.

Qt.point(int x, int y)

This function returns a Point with the specified x and y coordinates.

Qt.size(int width, int height)

This function returns as Size with the specified width and height.

Qt.vector3d(real x, real y, real z)

This function returns a Vector3D with the specified x, y and z.

Functions

The Qt object also contains the following miscellaneous functions which expose Qt functionality for use in QML.

Qt.lighter(color baseColor)

This function returns a color 50% lighter than baseColor. See QColor::lighter() for further details.

Qt.darker(color baseColor)

This function returns a color 50% darker than baseColor. See QColor::darker() for further details.

Qt.tint(color baseColor, color tintColor)

This function allows tinting one color with another.

The tint color should usually be mostly transparent, or you will not be able to see the underlying color. The below example provides a slight red tint by having the tint color be pure red which is only 1/16th opaque.

 Rectangle { x: 0; width: 80; height: 80; color: "lightsteelblue" }
 Rectangle { x: 100; width: 80; height: 80; color: Qt.tint("lightsteelblue", "#10FF0000") }

Tint is most useful when a subtle change is intended to be conveyed due to some event; you can then use tinting to more effectively tune the visible color.

Qt.closestAngle(number fromAngle, number toAngle)

This function returns an equivalent angle to toAngle, such that the difference between fromAngle and toAngle is never more than 180 degrees. This is useful when animating angles using a NumberAnimation, which does not know about equivalent angles, when you always want to take the shortest path.

For example, the following would rotate myItem counterclockwise from 350 degrees to 10 degrees, for a total of 340 degrees of rotation.

 NumberAnimation { target: myItem; property: "rotation"; from: 350; to: 10 }

while the following would rotate myItem clockwise from 350 degrees to 370 degrees (which is visually equivilant to 10 degrees), for a total of 20 degrees of rotation.

 NumberAnimation { target: myItem; property: "rotation"; from: 350; to: Qt.closetAngle(350, 10) }

Qt.playSound(url soundLocation)

This function plays the audio file located at soundLocation. Only .wav files are supported.

Qt.openUrlExternally(url target)

This function attempts to open the specified target url in an external application, based on the user's desktop preferences. It will return true if it succeeds, and false otherwise.

Qt.md5(data)

This function returns a hex string of the md5 hash of data.

Dynamic Object Creation

The following functions on the global object allow you to dynamically create QML items from files or strings. See Dynamic Object Management for an overview of their use.

createComponent(url file)

This function takes the URL of a QML file as its only argument. It returns a component object which can be used to create and load that QML file.

Example QML script is below. Remember that QML files that might be loaded over the network cannot be expected to be ready immediately.

         var component;
         var sprite;
         function finishCreation(){
             if(component.isReady()){
                 sprite = component.createObject();
                 if(sprite == 0){
                     // Error Handling
                 }else{
                     sprite.parent = page;
                     sprite.x = 200;
                     //...
                 }
             }else if(component.isError()){
                 // Error Handling
             }
         }

         component = createComponent("Sprite.qml");
         if(component.isReady()){
             finishCreation();
         }else{
             component.statusChanged.connect(finishCreation);
         }

If you are certain the files will be local, you could simplify to

         component = createComponent("Sprite.qml");
         sprite = component.createObject();
         if(sprite == 0){
             // Error Handling
             console.log(component.errorsString());
         }else{
             sprite.parent = page;
             sprite.x = 200;
             //...
         }

If you want to just create an arbitrary string of QML, instead of loading a QML file, consider the createQmlObject() function.

createQmlObject(string qml, object parent, string filepath)

Creates a new object from the specified string of QML. It requires a second argument, which is the id of an existing QML object to use as the new object's parent. If a third argument is provided, this is used for error reporting as the filepath that the QML came from.

Example (where targetItem is the id of an existing QML item):

     newObject = createQmlObject('import Qt 4.6; Rectangle {color: "red"; width: 20; height: 20}',
         targetItem, "dynamicSnippet1");

This function is intended for use inside QML only. It is intended to behave similarly to eval, but for creating QML elements.

Returns the created object, or null if there is an error. In the case of an error, details of the error are output using qWarning().

Note that this function returns immediately, and therefore may not work if the QML loads new components. If you are trying to load a new component, for example from a QML file, consider the createComponent() function instead. 'New components' refers to external QML files that have not yet been loaded, and so it is safe to use createQmlObject to load built-in components.

Asynchronous JavaScript and XML

QML script supports the XMLHttpRequest object, which can be used to asynchronously obtain data from over a network.

XMLHttpRequest()

In QML you can construct an XMLHttpRequest object just like in a web browser! TODO: Real documentation for this object.

Offline Storage API

The openDatabase() and related functions provide the ability to access local offline storage in an SQL database.

These databases are user-specific and QML-specific. They are stored in the Databases subdirectory of QDeclarativeEngine::offlineStoragePath(), currently as SQLite databases.

The API conforms to the Synchronous API of the HTML5 Web Database API, W3C Working Draft 29 October 2009.

The API can be used from JavaScript functions in your QML:

 import Qt 4.6

 Text {
     Script {
         function findGreetings() {
             var db = openDatabaseSync("QDeclarativeExampleDB", "1.0", "The Example QML SQL!", 1000000);

             db.transaction(
                 function(tx) {
                     // Create the database if it doesn't already exist
                     tx.executeSql('CREATE TABLE IF NOT EXISTS Greeting(salutation TEXT, salutee TEXT)');

                     // Add (another) greeting row
                     tx.executeSql('INSERT INTO Greeting VALUES(?, ?)', [ 'hello', 'world' ]);

                     // Show all added greetings
                     var rs = tx.executeSql('SELECT * FROM Greeting');

                     var r = ""
                     for(var i = 0; i < rs.rows.length; i++) {
                         r += rs.rows.item(i).salutation + ", " + rs.rows.item(i).salutee + "\n"
                     }
                     text = r
                 }
             )
         }
     }
     text: "?"
     Component.onCompleted: findGreetings()
 }

When a database is first created, an INI file is also created specifying its characteristics:

KeyValue
NameThe name of the database passed to openDatabase()
VersionThe version of the database passed to openDatabase()
DescriptionThe description of the database passed to openDatabase()
EstimatedSizeThe estimated size of the database passed to openDatabase()
DriverCurrently "QSQLITE"

This data can be used by application tools.


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt 4.7.0