Qt Script for Applications · Home · Tutorial · Classes · Functions · Language · QSA Workbench · Qt Documentation · www.trolltech.com

# Qt Script: Language Reference

## Introduction

Qt Script for Application's scripting language is called Qt Script, and it is an implementation of a subset of ECMAScript 4.0. ECMAScript is also called JavaScript or JScript by some vendors.

Qt Script provides the language features of ECMAScript, for example, while loops, class and function definitions, etc.

Qt Script also supports Trolltech's innovative signals and slots mechanism. Signals and slots provide type-safe inter-object communication that supercedes the crash-prone callbacks and message maps approaches used by older tools.

This language reference describes the language features provided by Qt Script. It is divided into the following chapters:

l{Qt Script Language Concepts} l{Built-in Types and Objects} l{Built-in Variables and Constants} l{Built-in Functions and Operators} l{Control Statements}

Readers are assumed to have a basic understanding of programming, and to have read the Getting Started with QSA guide that introduces Qt Script.

## Qt Script Language Concepts

This chapter describes the concepts behind Qt Script, Qt Script for Application's implementation of ECMAScript.

### Identifiers, Variables and Constants

Qt Script identifiers match the regex pattern [_A-Za-z][_A-Za-z0-9]*. Identifiers are used for variables, constants, class names, function names and labels.

ECMAScript reserves some words which are valid identifiers for its own use. See the Built-in Functions and Operators chapter for the complete list.

Variables are declared using the var keyword:

            var a;               // undefined
            var c = "foliage";   // the string "foliage"
            x = 1;               // global variable

If a variable has a type specified, i.e. by appending ': typename' after its name, only objects of the given type should be assigned to the variable. Variables declared with var are local to their enclosing block.

If a variable is assigned to without being declared, it is automatically declared as a global variable. Using global variables can make your code difficult to debug and maintain and is not recommended.

Constants are declared using the const keyword:

            const x = "Willow";
            const y = 42;

Constants must be defined at the point of declaration, because they cannot be changed later. If an attempt is made to assign to a constant, the Qt Script for Application interpreter will issue an error message and stop.

Constants are public globals if they are declared outside of any enclosing braces. When declared within the scope of some braces, e.g. within an if statment, their scope is local to the enclosing block.

### Classes and Methods

Qt Script is a fully object oriented language. Classes can be defined as shown below in the source files of a project.

Example:

            class Circle {
                var m_x;
                var m_y;
                var m_r;

                function Circle( posx, posy, radius )
                {
                    m_x = posx;
                    m_y = posy;
                    m_r = radius;
                }
                function setX( posx ) { m_x = posy; }
                function setY( posy ) { m_y = posy; }
                function setR( radius ) { m_r = radius; }
                function x() { return m_x; }
                function y() { return m_y; }
                function r() { return m_r; }
            }

            class ColorCircle extends Circle {
                var m_rgb;

                function ColorCircle( posx, posy, radius, rgbcolor)
                {
                    Circle( posx, posy, radius );
                    m_rgb = rgbcolor;
                }
                function setRgb( rgbcolor ) { m_rgb = rgbcolor; }
                function rgb() { return m_rgb; }
            }

A class's constructor is the function which has the same (case-sensitive) name as the class itself. The constructor should not contain an explicit return statement; it will return an object of its type automatically. Qt Script does not have a destructor function (a function that is called when the class is destroyed), for a class.

The class's member variables are declared with var, and its member functions (methods) with function.

The object instance itself is referred to using the this operator. Inside a member function of a class, member variables and member functions can be accessed with an explicit this (e.g. `this.x = posx;`). This is not required, but can sometimes help to increase visibility.

Qt Script supports single inheritance, and if a class inherits from another class, the superclass's constructor can be called with super().

See also class, function, Function type, function operator.

Qualified Names

When you declare an object of a particular type, the object itself becomes, in effect, a namespace. For example, in Qt Script for Application there is a function called `Math.sin()`. If you wanted to have a sin() function in your own class that would not be a problem, because objects of your class would call the function using the `object.function()` syntax. The period is used to distinguish the namespace a particular identifier belongs to.

For example, in a Qt Script for Application GUI application, every application object belongs to the `Application` object. This can lead to some rather lengthy code, for example `Application.Dialog.ListBox.count`. Such long names can often be shortened, for example, within a signal handler, e.g. `this.ListBox.count`. In practice, Qt Script for Application is intelligent enough to work out the fully qualified name, so the code you would actually write is simply `ListBox.count`. The only time that you need to qualify your names is when an unqualified name is ambiguous.

#### Class Properties

A property is an undeclared variable that can be written to and accessed if the class supports properties. The classes supporting properties are Object, the application objects and the classes provided by the object and wrapper factories.

        var obj = new Object
        object.myProperty = 100;

The class Object does not define the variable `myProperty`, but since the class supports properties, we can define the variable with that name on the fly and use it later. Properties are associated with the object they are assigned to, so even though the object `obj` in the example above gets the property `myProperty`, it does not mean that other objects of type `Object` will have the `myProperty` property, unless explicitly stated.

### Comments

Qt Script supports the same commenting syntax as C++. One line comments may appear on a line of their own, or after the statements on a line. Multi-line comments may appear anywhere.

        // A one line comment.

        /*
            A multi-line
            comment.
        */

## Built-in Types and Objects

Qt Script provides a variety of types and built-in objects. The types covered in the following sections are built into the Qt Script interpreter.

The built-in types include Array, Boolean, Date, Function type Number, Object, Point, Rect, RegExp, Size, String, Color, Palette, ColorGroup, ByteArray, Font and Pixmap.

The built-in objects include Math and System.

### Built-in Types

These are in some sense, Qt Script's 'native' datatypes.

#### Array

An Array is a datatype which contains a named list of items. The items can be any Qt Script object. Multi-dimensional arrays are achieved by setting array items to be arrays themselves.

Arrays can be extended dynamically simply by creating items at non-existent index positions. Items can also be added using `push()`, `unshift()` and `splice()`. Arrays can be concatenated together using `concat()`. Items can be extracted using `pop()`, `shift()` and `slice()`. Items can be deleted using `splice()`. Arrays can be turned into strings using `join()` or `Array::toString()`. Use `reverse()` to reverse the items in an array, and `sort()` to sort the items. The `sort()` function can be passed a comparison function for customized sort orders.

In general, operations that copy array items perform a deep copy on items that are `Number` or `String` objects, and a shallow copy on other objects.

##### Array Construction

Arrays can be constructed from array literals or using the new operator:

            var mammals = [ "human", "dolphin", "elephant", "monkey" ];
            var plants = new Array( "flower", "tree", "shrub" );
            var things = [];
            for ( i = 0; i < mammals.length; i++ ) {
                things[i] = new Array( 2 );
                things[i][0] = mammals[i];
                things[i][1] = plants[i];
            }

Arrays can be initialized with a size, but with all items undefined:

            var a = new Array( 10 ); // 10 items

##### Array Access

Array items are accessed via their names. Names can be either integers or strings.

Example:

            var m2 = mammals[2];
            mammals[2] = "gorilla";
            var thing = things[2][1]

The first statement retrieves the value of the third item of the `mammals` array and assigns it to `m2`, which now contains "monkey". The second statement replaces the third item of the `mammals` array with the value "gorilla". The third statement retrieves the second item of the third item's array from the `things` array and assigns it to `thing`, which now contains "shrub".

As stated above, it is also possible to access the arrays using strings. These act as normal properties, and can be accessed either using the square bracked operator ([]) or by directly dereferencing the array object and specifying the property name (.name). These two accessor types can be mixed freely as seen below with the `address` and `phoneNumber` properties.

            var names = [];
            names["first"] = "John";
            names["last"] = "Doe";
            var firstName = names["first"];
            var lastName = names["last"];

            names["address"] = "Somewhere street 2";
            names.phoneNumber = "+0123456789";
            var address = names.address;
            var phoneNumber = names["phoneNumber"];

##### Array Properties

- length : Number; Holds the number of items in the array. Items with string keys are excluded from the length property.

##### Array Functions

- concat( a1 : Array, a2 : Array ... aN : Array) : Array;

              var x = new Array( "a", "b", "c" );
              var y = x.concat( [ "d", "e" ], [ 90, 100 ] );
              // y == [ "a", "b", "c", "d", "e", 90, 100 ]

  Concatenates the array with one or more other arrays in the order given, and returns a single array.

- join( optSeparator : String ) : String;

              var x = new Array( "a", "b", "c" );
              var y = x.join();         // y == "a,b,c"
              var z = x.join( " * " );  // y == "a * b * c"

  Joins all the items of an array together, separated by commas, or by the specified `optSeparator`.

- pop() : Object;

              var x = new Array( "a", "b", "c" );
              var y = x.pop(); // y == "c"  x == [ "a", "b" ]

  Pops (i.e. removes) the top-most (right-most) item off the array and returns it.

- push( item1, optItem2, ... optItemN );

              var x = new Array( "a", "b", "c" );
              x.push( 121 ); // x == [ "a", "b", "c", 121 ]

  Pushes (i.e. inserts) the given items onto the top (right) end of the array. The function returns the new length of the array.

- reverse();

              var x = new Array( "a", "b", "c", "d" );
              x.reverse(); // x == [ "d", "c", "b", "a" ]

  Reverses the items in the array.

- shift() : Object;

              var x = new Array( "a", "b", "c" );
              var y = x.shift(); // y == "a"  x == [ "b", "c" ]

  Shifts (i.e. removes) the bottom-most (left-most) item off the array and returns it.

- slice( startIndex : Number, optEndIndex : Number ) : Array;

              var x = new Array( "a", "b", "c", "d" );
              var y = x.slice( 1, 3 ); // y == [ "b", "c" ]
              var z = x.slice( 2 );    // z == [ "c", "d" ]

  Copies a slice of the array from the item with the given starting index, `startIndex`, to the item before the item with the given ending index, `optEndIndex`. If no ending index is given, all items from the starting index onward are sliced.

- sort( optComparisonFunction : function );

              var x = new Array( "d", "x", "a", "c" );
              x.sort(); // x == [ "a", "c", "d", "x" ]

  Sorts the items in the array using string comparison. For customized sorting, pass the sort() function a comparison function, `optComparisonFunction`, that has the following signature and behavior:

              function comparisonFunction( a, b ) // signature

  The function must return an integer as follows:

  - -1 if a < b
  - 0 if a == b
  - 1 if a > b

  Example:

              function numerically( a, b ) { return a < b ? -1 : a > b ? 1 : 0; }
              var x = new Array( 8, 90, 1, 4, 843, 221 );
              x.sort( numerically ); // x == [ 1, 4, 8, 90, 221, 843 ]

- splice( startIndex : Number, replacementCount : Number, optItem1, ... optItemN );

              var x = new Array( "a", "b", "c", "d" );

              // 2nd argument 0, plus new items   ==> insertion
              x.splice( 1, 0, "X", "Y" );
              // x == [ "a", "X", "Y", "b", "c", "d" ]

              // 2nd argument > 0, and no items   ==> deletion
              x.splice( 2, 1 );
              // x == [ "a", "X", "b", "c", "d" ]

              // 2nd argument > 0, plus new items ==> replacement
              x.splice( 3, 2, "Z" );
              // x == [ "a", "X", "b", "Z" ]

  Splices items into the array and out of the array. The first argument, `startIndex`, is the start index. The second argument, `replacementCount`, is the number of items that are to be replaced. Make the second argument 0 if you are simply inserting items. The remaining arguments are the items to be inserted. If you are simply deleting items, the second argument must be > 0 (i.e. the number of items to delete), and there must be no new items given.

- toString() : String;

              var x = new Array( "a", "b", "c" );
              var y = x.toString();  // y == "a,b,c"
              var z = x.join();      // y == "a,b,c"

  Joins all the items of an array together, separated by commas. This function is used when the array is used in the context of a string concatenation or is used as a text value, e.g. for printing. Use `join()` if you want to use your own separator.

- unshift( expression : String, optExpression1, ... opExpressionN )

              var x = new Array( "a", "b", "c" );
              x.unshift( 121 ); // x == [ 121, "a", "b", "c" ]

  Unshifts (i.e. inserts) the given items at the bottom (left) end of the array.

#### Boolean

ECMAScript provides a Boolean data type. In general, creating objects of this type is not recommended since the behavior will probably not be what you would expect.

Instead, use the boolean constants `true` and `false` as required. Any expression can be evaluated in a boolean context, e.g. in an if statement. If the expression's value is `0`, `null`, `false`, NaN, undefined or the empty string `""`, the expression is `false`; otherwise the expression is `true`.

#### Date

Instances of the Date class are used to store and manipulate dates and times.

A variety of get functions are provided to obtain the date, time or relevant parts, for example, `getDay()`, `getYear()`, `getHours()`, `getMilliseconds()`, `getMinutes()`, `getMonth()`, `getSeconds()`, `getTime()`.

A complementary set of functions are also provided, including `setYear()`, `setHours()`, `setMilliseconds()`, `setMinutes()`, `setMonth()`, `setSeconds()`, `setTime()`.

The functions operate using local time.

Conversion between Date objects to and from strings are provided by `parse()` and `Date::toString()`.

Elapsed time (in milliseconds) can be obtained by creating two dates, casting them to `Number` and subtracting one value from the other.

        var date1 = new Date();
        // time flies..
        var date2 = new Date();
        var timedifference = date2.getTime() - date1.getTime();

##### Static Date Functions

- parse( dateString : String ) : Number;

              var d = new Date( Date.parse( "1976-01-25T22:30:00" ) );
              d = Date.parse( "1976-01-25T22:30:00" );

  This is a static function that parses a string, `dateString`, which represents a particular date and time. It returns the number of milliseconds since midnight on the 1st January 1970. The string must be in the ISO 8601 extended format: `YYYY-MM-DD` or with time `YYYY-MM-DDTHH:MM:SS`.

##### Date Construction

        Date()
        Date( milliseconds )
        Date( year, month, day, optHour, optMinutes, optSeconds, optMilliseconds )

            var today = new Date();
            var d = new Date( 1234567 );
            var date = new Date( 1994, 4, 21 );
            var moment = new Date( 1968, 5, 11, 23, 55, 30 );

Dates can be constructed with no arguments, in which case the value is the date and time at the moment of construction using local time. A single integer argument is taken as the number of milliseconds since midnight on the 1st January 1970.

##### Date Functions

- getDate() : Number;

              var d = new Date( 1975, 12, 25 );
              var x = d.getDate();  // x == 25

  Returns the day of the month using local time. The value is always in the range 1..31.

- getDay() : Number;

              var d = new Date( 1975, 12, 25, 22, 30, 15 );
              var x = d.getDay();  // x == 4

  Returns the day of the week using local time. The value is always in the range 1..7, with the week considered to begin on Monday.

  Example:

              var IndexToDay = [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" ];
              var d = new Date( 1975, 12, 28 );
              System.println( IndexToDay[ d.getDay() - 1 ] ); // Prints "Sun"

- getYear() : Number;

              var d = new Date( 1975, 12, 25 );
              var x = d.getYear();  // x == 1975

  Returns the year using local time.

- getHours() : Number;

              var d = new Date( 1975, 12, 25, 22 );
              var x = d.getHours();  // x == 22

  Returns the hour using local time. The value is always in the range 0..23.

- getMilliseconds() : Number;

              var d = new Date( 1975, 12, 25, 22 );
              var x = d.getMilliseconds();  // x == 0

  Returns the milliseconds component of the date using local time. The value is always in the range 0..999. In the example, `x` is 0, because no milliseconds were specified, and the default for unspecified components of the time is 0.

- getMinutes() : Number;

              var d = new Date( 1975, 12, 25, 22, 30 );
              var x = d.getMinutes();  // x == 30

  Returns the minutes component of the date using local time. The value is always in the range 0..59.

- getMonth() : Number;

              var d = new Date( 1975, 12, 25, 22, 30 );
              var x = d.getMonth();  // x == 12

  Returns the months component of the date using local time. The value is always in the range 1..12.

  Example:

              var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
              var d = new Date( 1975, 12, 25 );
              System.println( IndexToMonth[ d.getMonth() - 1] ); // Prints "Dec"

- getSeconds() : Number;

              var d = new Date( 1975, 12, 25, 22, 30 );
              var x = d.getSeconds();  // x == 0

  Returns the seconds component of the date using local time. The value is always in the range 0..59. In the example `x` is 0 because no seconds were specified, and the default for unspecified components of the time is 0.

- getTime() : Number;

              var d = new Date( 1975, 12, 25, 22, 30 );
              var x = d.getTime();  // x == 1.91457e+11

  Returns the number of milliseconds since midnight on the 1st January 1970 using local time.

- setDate( dayOfTheMonth : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setDate( 30 );  // d == 1975-12-30T22:30:00

  Sets the day of the month to the specified `dayOfTheMonth` in local time.

- setYear( year : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setYear( 1980 );         // d == 1980-12-30T22:30:00
              d.setYear( 1980, 11, 2 );  // d == 1980-12-02T22:30:00

  Sets the year to the specified `year` in local time. If the month, optMonth is specified, it must be in the range 0..11. If the optDayOfTheMonth is specified it must be in the range 1..31.

- setHours( hour : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setHours( 10 );  // d == 1980-12-30T10:30:00

  Sets the `hour` to the specified hour, which must be in the range 0..23, in local time. The minutes, seconds and milliseconds past the hour (`optMinutes`, `optSeconds` and `optMilliseconds`) can also be specified.

- setMilliseconds( milliseconds : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setMilliseconds( 998 );  // d == 1980-12-30T10:30:00:998

  Sets the `milliseconds` component of the date to the specified value in local time.

- setMinutes( minutes : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setMinutes( 15 );  // d == 1980-12-30T10:15:00

  Sets the `minutes` to the specified minutes, which must be in the range 0..59, in local time. The seconds and milliseconds past the minute (`optSeconds` and `optMilliseconds`) can also be specified.

- setMonth( month : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setMonth( 0, 11 );  // d == 1980-01-11T22:30:00

  Sets the `month` to the specified month, which must be in the range 0..11, in local time. The day of the month (`optDayOfTheMonth`) may also be specified.

- setSeconds()

  `setSeconds( seconds, optMilliseconds )`

              var d = new Date( 1975, 12, 25, 22, 30 );
              d.setSeconds( 25 );  // d == 1980-12-30T22:30:25

  Sets the `seconds` to the specified seconds, which must be in the range 0..59, in local time. The milliseconds past the minute (optMilliseconds) can also be specified.

- setTime( milliseconds : Number );

              var d = new Date( 1975, 12, 25, 22, 30 );
              var duplicate = new Date();
              duplicate.setTime( d.getTime() );

  Sets the date and time to the local date and time given in terms of `milliseconds` since midnight on the 1st January 1970.

- toString() : String;

              var d = new Date( 1975, 12, 25, 22, 30 );
              var s = d.toString(); // s == "1975-12-25T22:30:00"

Converts the date into a string on the ISO 8601 extended format: `YYYY-MM-DDTHH:MM:SS`.

#### Function Type

Functions are normally defined in the application's source code. In some situations it is desirable to create functions at run time.

            var min = new Function( "x", "y", "return x < y ? x : y;" );
            var m = min( 68, 9 ); // m == 9

The first arguments are the names of the parameters; the last argument is a string which contains the function's definition. It is also possible to supply the list of argument names as one comma separated string.

            var min = new Function( "x,y", "return x < y ? x : y;" );

Variable numbers of arguments are also supported, using the arguments array, for example:

            max = new Function(
                  "var max = 0;"
                + "for ( var i = 0; i < arguments.length; i++ ) {"
                + "   if ( arguments[ i ] > max ) max = arguments[ i ];"
                + "}"
                + "return max;"
                );
            System.println( max( 50, 16, 24, 99, 1, 97 ) ); // Prints 99

#### Number

A Number is a datatype that represents a number. In most sittuations, programmers will use numeric literals like 3.142 directly in code. The Number datatype is useful for obtaining system limits, e.g. `MIN_VALUE` and `MAX_VALUE`, and for performing number to string conversions with toString()

##### Number Construction

Numbers are not normally constructed, but instead created by simple assignment, e.g.

            var x = 3.142;

##### Number Properties

- MAX_VALUE : Number; The maximum value for floating point values.
- MIN_VALUE : Number; The minimum value for floating point values.

A numeric variable can hold a non-numeric value, in which case isNaN() returns `true`. The result of an arithmetic expression may exceed the maximum or minimum representable values in which case the value of the expression will be Infinity, and isFinite() will return `false`.

##### Number Functions

- toString() : String; Returns the number as a string value.

#### Object

An Object is the base type for all Qt Script objects.

Object provides a toString() function which is usually overridden by subclasses.

#### Point

The Point class provides an implementation of a two dimensional point.

The Point class provides three different constructors.

            var point = new Point( 20, 30 );
            var duplicate = new Point( point ); // 20, 30
            var zero = new Point();             // 0, 0

##### Point Properties

- x : Number; The x position of the point.
- y : Number; The y position of the point.

            var p = new Point( 100, 200 );
            System.println( "Point is: " + p.x + ", " + p.y );

#### Rect

A Rect object represents a rectangle.

The rectangle class provides three constructors.

            var rect = new Rect( 10, 20, 30, 40 ); // x=10, y=20, width=30, height=40
            var duplicate = new Rect( rect );      // x=10, y=20, width=30, height=40
            var empty = new Rect();                // x=0, y=0, width=0, height=0

##### Rect Properties

- x : Number; The left position of the rectangle.
- y : Number; The right position of the rectangle.
- width : Number; The width of the rectangle.
- height : Number; The height of the rectangle.
- top : Number; The position of the top of the rectangle. This is defined as `top = y`.
- bottom : Number; The position of the bottom of the rectangle. This is defined as `bottom = y + height + 1`.
- left : Number; The position of the rectangle's left side. This is defined as `left = x`
- right : Number; The position of the rectangle's right side. This is defined as `right = x + width + 1`.
- center : Point; The center of the rectangle.

##### Rect Functions

- isNull() : Boolean;

              var empty = new Rect();
              empty.isNull(); // true;

              var square = new Rect( 10, 10, 10, 10 );
              square.isNull(); // false;

  Returns true if the rectangle has a width and height of 0.

- isEmpty() : Boolean;

              var rect = new Rect( 10, 10, -10, -10 );
              rect.isEmpty(); // true

              var rect = new Rect( 10, 10, 10, 10 );
              rect.isEmpty(); // false

  Returns true if the rectangle is empty, meaning that it has width and/or height that is negative.

- contains( otherRect : Rect ) : Boolean;

              new Rect( 0, 0, 100, 100 ).contains( new Rect( 10, 10, 10, 10 ) ); // true
              new rect( 10, 10, 10, 10 ).contains( new Rect( 0, 0, 100, 100 ) ); // false

  Returns true if the rectangle contains the other rectangle.

- intersection( otherRect : Rect ) : Rect; Returns the intersection between this rectangle and another rectangle. The intersection of two rectangles is the part of the rectangles that overlap. If they do not overlap, an empty rectangle is returned.
- union( otherRect : Rect ) : Rect; Returns the union of two rectangles. The union is a rectangle large enough to encompass both rectangles.
- intersects( otherRect : Rect ) : Boolean; Returns true if this rectangle intersects the other rectangle.
- normalize(); Normalizes this rectangle. This means changing the prefix of the width and/or height if they are negative. After being normalized, a rectangle will no longer be empty.
- moveLeft( pos : Number ); Moves the rectangle so that its `left` property is equal to `pos`.
- moveRight( pos : Number ); Moves the rectangle so that its `right` property is equal to `pos`.
- moveTop( pos : Number ); Moves the rectangle so that its `top` property is equal to `pos`.
- moveBottom( pos : Number ); Moves the rectangle so that its `bottom` property is equal to `pos`.
- moveBy( dx : Number, dy : Number ); Translates the rectangle by `dx` and `dy`. `dx` and `dy` will be added to `x` and `y`, and `width` and `height` will be left unchanged.

#### Size

The Size class represents a two dimensional size. The size is represented using width and height.

The Size class provides three construtors:

            var size = new Size( 100, 200 ); // width = 100, height = 200
            var duplicate = new Size( size ); // width = 100, height = 200
            var empty = new Size(); // width = 0, height = 0

##### Size Properties

- width : Number; The width of the size.
- height : Number; The height of the size.

##### Size Functions

- translate(); The translate function swaps the width and height of the size.

#### RegExp

A RegExp is a regular expression matcher for strings.

Regular expressions can be created either by using the `/expression/` syntax or by using the RegExp constructor as shown below. Note that when using the RegExp constructor, a string is passed, and all backslashes must be escaped using an extra backslash, i.e. `\\d`. Below are two ways to create regular expressions that matches the pattern "QUANTITY=471 # Order quantity" and gets the number 471.

            var directRegex = /([A-Z]+)=(\d+)/;
            var str = "QUANTITY=471 # Order quantity";
            str.match(directRegex);
            directRegex.capturedTexts[2]; // "471";

            var indirectRegex = new RegExp( "([A-Z]+)=(\\d+)" );

##### RegExp Properties

- valid : Boolean; Returns true if the regular expression is syntactically valid; otherwise returns false.
- empty : Boolean; Returns true if the pattern is empty; otherwise returns false.
- matchedLength : Number; The length of the last matched string, or -1 if there was no match.
- capturedTexts : String[]; An array of all the captured texts from the previous match. This can be empty.
- global : Boolean; Specifies that the regexp should be matched globally. A global regexp will match every occurrence (i.e. as many times as possible), whereas a non-global regexp will match at most once (at the first match it encounters). This is particularly relevant for replace where every occurance of a pattern will be replaced when global is true.

  A regular expression can be set to global either by setting the global property on a regexp object or by specifying a trailing `g` in the pattern.

          var re = /mypattern/g;     // Global by method #1

          var re = /mypattern/;
          re.global = true           // Global by method #2

- ignoreCase : Boolean; Specifies that the regexp ignores case when matching. Case-insensitivity can is enabled by either specifying a trailing `i` after the pattern or by setting the `ignoreCase` property.

          var re = /mypattern/i;     // Case-insensitive by method #1

          var re = /mypattern/;
          re.ignoreCase = true;      // Case-insensitive by method #2

##### RegExp Functions

- toString() : String; Returns the regular expression pattern as a string.
- search( text : String ) : Number;

              var re = /\d+ cm/; // matches one or more digits followed by space then 'cm'
              re.search( "A meter is 100 cm long" ); // returns 11

  Searches `text` for the pattern defined by the regular expression. The function returns the position in the text of the first match or -1 if no match is found.

- searchRev( text : String ) : Number; Same as `search()`, but searchRev searches from the end of the text.
- exactMatch( text : String ) : Boolean; Returns true if `text` exactly matches the pattern in this regular expresssion; otherwise returns false.
- cap( nth : Number ) : String;

              re = /name: ([a-zA-Z ]+)/;
              re.search( "name: John Doe, age: 42" );
              re.cap(0);  // returns "name: John Doe"
              re.cap(1);  // returns "John Doe"
              re.cap(2);  // returns undefined, no more captures.

  Returns the `nth` capture of the pattern in the previously matched text. The first captured string (`cap(0)` ) is the part of the string that matches the pattern itself, if there is a match. The following captured strings are the parts of the pattern enclosed by parenthesis. In the example above we try to capture `([a-zA-Z ]+)`, which captures a sequence of one or more letters and spaces after the `name:` part of the string.

- pos( nth : Number ) : Number;

              re = /name: ([a-zA-Z ]+)/;
              re.search( "name: John Doe, age: 42" );
              re.pos(0); // returns 0, position of "name: John Doe"
              re.pos(1); // returns 6, position of "John Doe"
              re.pos(2); // returns -1, no more captures

  Returns the position of the `nth` captured text in the search string.

#### String

A String is a sequence of zero or more Unicode characters. Qt Script's String class uses the Qt QString class's functions and syntax.

Strings can be created and concatenated as follows.

            var text = "this is a";
            var another = new String( "text" );
            var concat = text + " " + another;  // concat == "this is a text"

##### String Properties

- length : Number; The length property specifies the length of the string.

##### Static String Functions

- fromCharCode ( static function )

              var s = String.fromCharCode( 65, 66, 67, 68 );
              System.println( s ); // prints "ABCD"

  Returns a string made up of the characters with code `code1`, `code2`, etc, according to their Unicode character codes.

##### String Functions

- charAt( pos : Number ) : String; Returns the character in the string at position `pos`. If the position is out of bounds, `undefined` is returned.
- charCodeAt( pos : Number ) : Number; Returns the character code of the character at position `pos` in the string. If the position is out of bounds, `undefined` is returned.
- indexOf( pattern : String or RegExp, pos : Number ) : Number; Returns the index of `pattern` in the string, starting at position `pos`. If no position is specified, the function starts at the beginning of the string. If the pattern is not found in the string, -1 is returned.
- lastIndexOf( pattern : String or RegExp, pos : Number ) : Number; Returns the last index of `pattern` in the string, starting at position `pos` and searching backwards from there. If no position is specified, the function starts at the end of the string. If the pattern is not found in the string, -1 is returned.
- match( pattern : RegExp ) : String; Returns the matched pattern if this string matches the pattern defined by `regexp`. If `regexp` is not a valid regular expression, `undefined` is returned.
- search( pattern : String or RegExp ) : String; same as find.
- searchRev( pattern : String or RegExp ) : String; same as findRev.
- replace( pattern : RegExp, newValue : String ) : String; Replaces the first occurrence of `pattern` in the string with `newvalue` if the pattern is found in the string. A modified copy of string is returned.

  If `pattern` is a regular expression with global set, all occurances of `pattern` in the string will be replaced.

- split( pattern : String or RegExp ) : String[]; Returns an array of strings containing this string split on each occurrence of `pattern`.
- substring( startIndex : Number, endIndex : Number ) : String; Returns a copy of this string which is the substring starting at `startIndex` and ending at `endIndex`.
- toLowerCase() : String; Returns a lowercase copy of this string.
- lower() : String; Same as toLowerCase().
- toUpperCase() : String; Returns an uppercase copy of this string.
- upper() : String; Same as toUpperCase().
- isEmpty() : Boolean; Returns true if the string is empty, i.e. has a length of 0; otherwise returns false.
- left( length : Number ) : String; Returns a substring containing the `length` leftmost characters of this string.
- right( length : Number ) : String; Returns a substring containing the `length` rightmost characters of this string.
- mid( start : Number, length : Number ) : String; Returns a copy of this string which is the substring starting a `start` and is `length` characters long.
- find( pattern : String or RegExp, pos : Number ) : Number; Returns the first position of `pattern` after `pos`. If the pattern is not found, -1 is returned. If `pos` is not specified, position 0 is used.
- findRev( pattern : Number, pos : Number ) : String; Returns the first position of `pattern` before or at `pos`, searching backward. If pattern is not found, -1 is returned. If `pos` is not specified, the search starts at the end of the string.
- startsWith( pattern : String or RegExp ) : Boolean; Returns true if the string starts with `pattern`; otherwise returns false.
- endsWith( pattern : String or RegExp ) : Boolean; Returns true if the string ends with `pattern`; otherwise returns false.
- arg( value : String or Number, fieldWidth : Number ) : String; This function will return a string that replaces the lowest numbered occurrence of %1, %2, ..., %9 with `value`.

  The `fieldWidth` parameter specifies the minimum amount of space that `value` is padded to. A positive `fieldWidth` will produce right-aligned text, whereas a negative `fieldWidth` will produce left-aligned text.

- argInt( value : Number, fieldWidth : Number, base : Number ) : String; This function behaves like arg above, but is specialized for the case where `value` is an integer.

  `value` is expressed in base `base`, which is 10 by default and must be between 2 and 36.

- argDec( value : Number, fieldWidth : Number, format : Number, precision : Number ) : String; This function behaves like `arg()` above, but is specialized for the case where `value` is a decimal value.

  Argument `value` is formatted according to the `format` specified, which is 'g' by default and can be any of the following:

  - `e` - format as [-]9.9e[+|-]999
  - `E` - format as [-]9.9E[+|-]999
  - `f` - format as [-]9.9
  - `g` - use `e` or `f` format, whichever is the most concise
  - `G` - use `E` or `f` format, whichever is the most concise

  With 'e', 'E', and 'f', `precision` is the number of digits after the decimal point. With 'g' and 'G', `precision` is the maximum number of significant digits (trailing zeroes are omitted).

#### Color

The Color class is used to represent colors. Instances of Color can be passed to C++ slots that take arguments of type QColor.

##### Color Properties

- red : Number; The red component of the color. This is a value between 0 and 255.
- green : Number; The green component of the color. This value is between 0 and 255.
- blue : Number; The blue component of the color. This value is between 0 and 255.
- name : String; The name of the color, if a matching name for the color exists; otherwise an empty string.
- rgb : Number; The rgb color code of the color. The color code is a bitmask of the form `0xRRGGBB`, where RR is the red component, GG is the green component, and BB is the blue component expressed as hexadecimal digits.
- hue : Number; The color's hue, as defined by the HSV color model.
- saturation : Number; The color's saturation, as defined by the HSV color model.
- value : Number; The colors's value, as defined by the HSV color model.

##### Color Functions

- setRgb( colorcode ); Sets the color code of the color. The value is a bitmask on the form 0xRRGGBB, where RR=red, GG=green, and BB=blue, all as hexadecimal digits.
- setRgb( red, green, blue ); Sets the red, green and blue color values of the color to `red`, `green` and `blue`.
- light() : Color; Returns a Color that is a lighter version of this one.
- dark() : Color; Returns a Color that is a darker version of this one.

#### Palette

The Palette class contains color groups for each widget state. A palette consists of three color groups: active, disabled, and inactive. All widgets contain a palette, and all widgets in Qt use their palette to draw themselves. This makes the user interface easily configurable and easier to keep consistent.

##### Palette Properties

- active : ColorGroup; The active color group is used for the window that has the keyboard focus.
- inactive : ColorGroup; The inactive color group is used for the other windows.
- disabled : ColorGroup; The disabled color group is used for widgets (not windows) that are disabled.

#### ColorGroup

The QColorGroup class contains a group of widget colors.

##### ColorGroup Properties

- background : Color; General background color.
- foreground : Color; General foreground color.
- base : Color; Used as background color for text entry widgets, for example; usually white or another light color.
- text : Color; The foreground color used with `base`.
- button : Color; General button background color.
- buttonText : Color; A foreground color used with the `button` color.
- light : Color; Used for 3D bevel and shadow effects. Lighter than `button` color.
- midlight : Color; Used for 3D bevel and shadow effects. Between `button` and `light`.
- dark : Color; Used for 3D bevel and shadow effects. Darker than `button`.
- mid : Color; Used for 3D bevel and shadow effects. Betwen `button` and `dark`.
- shadow : Color; Used for 3D bevel and shadow effects. A very dark color.
- highlight : Color; A color to indicate a selected item or the current item.
- highlightedText : Color; A text color that contrasts with `highlight`.

#### ByteArray

The ByteArray class is an array optimized for storing raw bytes. Instances of ByteArray can be passed to C++ slots that take arguments of type QByteArray.

##### ByteArray Properties

- length : Number; The number of bytes in the byte array. This value is read-only.
- size : Number; The number of bytes in the byte array. This value is read-only.

##### ByteArray Functions

- charAt( index : Number ) : String; Returns the character (byte) at the position index in the byte array. The byte is returned as a string.

#### Font

The Font class represents a font. Instances of Font can be passed to C++ slots that take arguments of type QFont.

##### Font Properties

- family : String; The fonts family or name, such as `SansSerif`.
- pointSize : Number; The point size of the font. A point is 1/72 inch. Using point size will give you a fixed sized independent of the device the font is used on. For instance, a screen has different resolution than a printer.
- pixelSize : Number; The pixel size of the font. The size of a pixel is determined by the device the font is used for. For instance, a printer may have a resolution of have 600 pixels/inch, whereas a monitor may only achieve 120 pixels/inch.
- bold : Boolean; True if the font is bold; otherwise false.
- italic : Boolean; True if the font is italic; otherwise false.
- underline : Boolean; True if the font is underline; otherwise false.
- strikeout : Boolean; True if the strikeout is on; otherwise false.

#### Pixmap

The Pixmap class can be used to represent images in QSA. Instances of Pixmap can be passed to C++ slots that take arguments of type QPixmap.

The Pixmap constructor can take a filename referring to an image that will then be loaded:

        var background = new Pixmap( "background.png" );

##### Pixmap Properties

- width : Number; The width of the pixmap. This value is read-only.
- height : Number; The height of the pixmap. This value is read-only.
- rect : Rect; The enclosing rectangle (0, 0, width, height) of the pixmap. This value is read-only.
- size : Size; The size of the rectangle. This value is read-only.
- depth : Number; The color depth of the pixmap. The pixmap depth is also called bits per pixel (bpp) or bit planes of a pixmap. A null pixmap has depth 0. This value is read-only.

##### Pixmap Functions

- isNull() : Boolean; Returns true if this is a null pixmap; otherwise returns false. A null pixmap has zero width, zero depth, and no contents.
- fill( color ); Fills the pixmap with the specified color.
- resize( size : Size ); Resizes the pixmap to the specified size.
- resize( width : Number, height : Number ); Resizes the pixmap to the specified dimensions.
- load( fileName : String ); Loads the pixmap data from the specified file.
- save( fileName : String ); Saves the pixmap to the specified file.

### Built-in Objects

The built-in `Math` object provides functions that include: `abs()`, `acos()` and `cos()`, `asin()` and `sin()`, `atan()`, `atan2()` and `tan()`, `ceil()`, `floor()` and `round()`, `exp()` and `log()`, `max()` and `min()`, `pow()` and `sqrt()`, `random()`, and `round()`.

The built-in `System` object provides functions including: `getenv()`, `setenv()`, `print()` and `println()`.

#### Math

The Math object always exists in a Qt Script program. Use the Math object to access mathematical constants and functions, e.g.

            with ( Math ) {
                var x = PI * 2;
                var angle = 1.3;
                var y = x * sin( angle );
            }

The Math object supports all the common mathematical functions, for example: `abs()`, `acos()` and `cos()`, `asin()` and `sin()`, `atan()`, `atan2()` and `tan()`, `ceil()`, `floor()` and `round()`, `exp()` and `log()`, `max()` and `min()`, `pow()` and `sqrt()`, `random()`, and `round()`.

See also, + operator, ++ operator, - operator, -- operator, * operator, / operator, % operator, -= operator, += operator, *= operator, /= operator and %= operator.

##### Math Properties

All the Math properties are read-only constants.

- E -- Eulers constant. The base for natural logarithms.
- LN2 -- Natural logarithm of 2.
- LN10 -- Natural logarithm of 10.
- LOG2E -- Base 2 logarithm of E.
- LOG10E -- Base 10 logarithm of E.
- PI -- Pi.
- SQRT1_2 -- Square root of 1/2.
- SQRT2 -- Square root of 2.

##### Math Functions

- abs( number : Number ) : Number;

  Returns the absolute value of the given `number`. The equivalent of

              x = x < 0 ? -x : x;

              var x = -99;
              var y = 99;
              with ( Math ) {
                  x = abs( x );
                  y = abs( y );
              }
              if ( x == y ) System.println( "equal" );

- acos( number : Number ) : Number; Returns the arccosine of the given `number` in radians between 0 and `Math.PI`. If the number is out of range, returns NaN.
- asin( number : Number ) : Number; Returns the arcsine of the given `number` in radians between `-Math.PI/2` and `Math.PI/2`. If the number is out of range, returns NaN.
- atan( number : Number ) : Number; Returns the arctangent of the given `number` in radians between `-Math.PI/2` and `Math.PI/2`. If the number is out of range, returns NaN.
- atan2( yCoord : Number, xCoord : Number ) : Number; Returns the counter-clockwise angle in radians between the positive x-axis and the point at (`xCoord`, `yCoord`). The value returned is always between `-Math.PI` and `Math.PI`.

  Example:

              function polar( x, y )
              {
                  return Math.atan2( y, x );
              }

- ceil( number : Number ) : Number; If the `number` is an integer, it returns the `number`. If the `number` is a floating point value, it returns the smallest integer greater than the `number`.

  Example:

              var x = 913.41;
              x = Math.ceil( x ); // x == 914
              var y = -33.97;
              y = Math.ceil( y ); // y == -33

- cos( number : Number ) : Number; Returns the cosine of the given `number`. The value will be in the range -1..1.
- exp( number : Number ) : Number; Returns `Math.E` raised to the power of the given `number`.
- floor( number : Number ) : Number; If the `number` is an integer, it returns the `number`. If the `number` is a floating point value, it returns the greatest integer less than the `number`.
- log( number : Number ) : Number; If the `number` is > 0, it returns the natural logarithm of the given `number`. If the `number` is 0, it returns `Infinity`. If the `number` is < 0, it returns NaN.
- max( number1 : Number, number2 : Number ) : Number; Returns the largest of `number1` and `number2`.
- min( number1 : Number, number2 : Number ) : Number; Returns the smallest of `number1` and `number2`.
- pow( number : Number, power : Number ) : Number; Returns the value of the `number` raised to the `power`.
- random() : Number; Returns a pseudo-random floating point number between 0 and 1. Pseudo random numbers are not truly random, but may be adequate for some applications, for example, games and simple simulations.
- round( number : Number ) : Number; Returns the `number` rounded to the nearest integer. If the fractional part of the `number` is >= 0.5, the `number` is rounded up; otherwise it is rounded down.
- sin( number : Number ) : Number; Returns the sine of the given `number`. The value will be in the range -1..1.
- sqrt( number : Number ) : Number; If the `number` is >= 0, it returns the square root. If the `number` is < 0, it returns NaN.
- tan( number : Number ) : Number; Returns the tangent of the given `number`.

#### System

The System object always exists in a Qt Script program. Use the System object to access and manipulate environment variables, e.g. with `getenv()` and `setenv()`, and to print text to the console with `print()` and `println()`.

##### System Functions

- getenv( environmentVariable : String ) : String; Returns the string stored in the given `environmentVariable`.

  Example:

              var q = System.getenv( "QTDIR" ); // q == "/usr/local/qt"

- print( expression : String ); Prints the `expression` (applying toString() if necessary) to the console (`stdout`).
- println( expression : String ); Prints the `expression` (applying toString() if necessary) to the console (`stdout`), followed by a newline.
- setenv( environmentVariable : String, value : String ); Sets the `environmentVariable` to the `value`. If the `environmentVariable` does not exist it is created. The environment is only changed within the context of the Qt Script process for the duration of the process.

## Built-in Variables and Constants

Qt Script for Application provides a number of convenient built-in constants and variables.

The built-in variables include arguments.

The built-in constants include Infinity, NaN and undefined.

### Built-in Variables

#### arguments

This is an Array of the arguments that were passed to the function. It only exists within the context of a function.

Example:

            function sum()
            {
                total = 0;
                for ( i = 0; i < arguments.length; i++ ) {
                    total += arguments[ i ];
                }
                return total;
            }

### Built-in Constants

#### Infinity

This is the value of any division by zero, i.e.

            var i = 1/0;

In Qt Script, division by zero does not raise an exception; instead it assigns the `Infinity` value as the result of the expression. Use isFinite() to test whether a value is finite or not.

#### NaN

Some functions that are supposed to return a numeric result may return `NaN` instead. Use isNaN() to check for this.

#### undefined

This is the value of a variable that does not have a defined value, i.e. has not been assigned to.

Example:

            var i;
            // ...
            if ( i == undefined ) {
                i = 77;
            }

In this example, if execution reaches the `if` statement, and `i` has not been assigned a value, it will be assigned the value 77.

## Built-in Functions and Operators

Qt Script for Application provides many useful built-in functions and operators.

The built-in functions include connect(), debug(), eval(), isFinite(), isNaN(), killTimer(), killTimers(), parseFloat(), parseInt() and startTimer().

Classes, functions, variables and constants are declared with class, function, var and const respectively.

ECMAScript reserves the following words for future use:

boolean, byte, char, debugger, double, enum, export, float, goto, implements, import, int, interface, long, native, short, synchronized, throws, transient and volatile.

It is unadvisable to use any of these words as identifiers.

### Built-in Functions

#### connect()

`connect( signallingObject, signal, receivingObject, slot )`

This function is used to create signals and slots connections between objects.

See the filter example program's example-script for an example.

`connect( sender, signal, functionRef )`

This function is used to create signals and slots connections between objects. functionRef can be a global function or a member of the class.

#### debug()

`debug( expression )`

Prints the expression (applying toString() if necessary) to the output (`stderr`), followed by a newline.

#### eval()

`eval( string )`

            var x = 57;
            var y = eval( "40 + x" ); // y == 97

This function parses and executes the contents of the string, taking the text to be valid Qt Script.

#### isFinite()

`isFinite( expression )`

Returns `true` if the expression's value is a number that is within range; otherwise returns `false`.

#### isNaN()

`isNaN( expression )`

Returns `true` if the expression's value is not a number; otherwise returns `false`.

Example:

            var x = parseFloat( "3.142" );
            var y = parseFloat( "haystack" );
            if ( isNaN( x ) ) debug( "x is not a number" );
            if ( isNaN( y ) ) debug( "y is not a number" );
            // Prints: "y is not a number"

#### killTimer()

`killTimer( timerId )`

Stops and deletes the timer with the given timerId. Any events that are triggered by the timer with timerId will no longer be triggered.

See killTimers() and startTimer().

#### killTimers()

`killTimers()`

Stops and deletes all timers that have been created with startTimer(). Any events that are triggered by any of these timers will no longer be triggered.

See killTimer() and startTimer().

#### parseFloat()

`parseFloat( string )`

Parses the string and returns the floating point number that the string represents or NaN if the parse fails. Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.

See also parseInt().

#### parseInt()

`parseInt( string, optBase )`

Parses the string and returns the integer that the string represents in the given base optBase, or NaN if the parse fails. If the base isn't specified, the base is determined as follows:

- base 16 (hexadecimal) if the first non-whitespace characters are "0x" or "0X";
- base 8 (octal) if the first non-whitespace character is "0";
- base 10 otherwise.

Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.

Example:

            var i = parseInt( "24" );       // i == 24
            var h = parseInt( "0xFF" );     // h == 255
            var x = parseInt( " 459xyz " ); // x == 459

See also parseFloat().

#### startTimer()

`var timerId = startTimer( interval, timeoutFunction )`

Creates a new timer. The timer's id is returned, although it isn't needed if you use killTimers(). The timer calls the timeoutFunction every interval milliseconds.

### Built-in Operators

The built-in operators include: + operator, ++ operator, - operator, -- operator, * operator, / operator, % operator, + string operator, += string operator, += operator, && operator, || operator, ! operator, & operator, ^ operator, | operator, ~ operator, << operator, >> operator, >>> operator, = operator, -= operator, *= operator, /= operator, %= operator, &= operator, ^= operator, |= operator, <<= operator, >>= operator, >>>= operator, == operator, != operator, === operator, !== operator, > operator, >= operator, ?: operator, , operator, function operator, in operator, instanceof operator, new operator, this operator and typeof operator.

#### Assignment Operators

These operators are used to assign the value of expressions to variables.

##### = operator

`var variable = expression;`

The assignment operator is used to assign the value of an expression to the variable.

It is an error to attempt to assign to a constant.

##### += operator

`variable += expression;`

This operator adds the value of the expression to the variable. It is the same as:

            variable = variable + expression;

but is shorter to write, and less error-prone.

See also += string operator.

##### -= operator

`variable -= expression;`

This operator subtracts the value of the expression from the variable.

##### *= operator

`variable *= expression;`

This operator multiplies the value of the expression by the value of the variable.

##### /= operator

`variable /= expression;`

This operator divides the value of the variable by the value of the expression.

##### %= operator

`variable %= expression;`

This operator divides the variable by the expression, and assigns the remainder of the division (which may be 0), to the variable.

##### &= operator

`variable &= expression;`

This operator performs a bit-wise AND on the value of the expression and the value of the variable, and assigns the result to the variable.

##### ^= operator

`variable ^= expression;`

This operator performs a bit-wise OR on the value of the expression and the value of the variable, and assigns the result to the variable.

##### |= operator

`variable |= expression;`

This operator performs a bit-wise OR on the value of the expression and the value of the variable, and assigns the result to the variable.

##### <<= operator

`variable <<= expression;`

This operator performs a bit-wise left shift on the variable by an expression number of bits. Zeros are shifted in from the right.

##### >>= operator

`variable >>= expression;`

This operator performs a bit-wise (sign-preserving) right shift on the variable by an expression number of bits.

##### >>>= operator

`variable >>>= expression;`

This operator performs a bit-wise (zero-padding) right shift on the variable by an expression number of bits.

#### Arithmetic Operators

These operators are used to perform arithmetic computations on their operands.

##### + operator

`operand1 + operand2`

This operator returns the result of adding the two operands (operand1 and operand2).

See also + string operator.

##### ++ operator

        ++operand; // pre-increment
        operand++; // post-increment

The pre-increment version of this operator increments the operand, and returns the value of the (now incremented) operand.

The post-incremented version of this operator returns the value of the operand, and then increments the operand.

##### - operator

        var result = operand1 - operand2; // subtraction
        operand = -operand;               // unary negation

The subtraction version of this operator returns the result of subtracting its second operand (operand2) from its first operand (operand1).

The unary negation version of this operator returns the result of negating (changing the sign) of its operand.

##### -- operator

        --operand; // pre-decrement
        operand--; // post-decrement

The pre-decrement version of this operator decrements the operand, and returns the value of the (now decremented) operand.

The post-decremented version of this operator returns the value of the operand, and then decrements the operand.

##### * operator

`operand1 * operand2`

This operator returns the result of multiplying the two operands (operand1 and operand2).

##### / operator

`operand1 / operand2`

This operator returns the result of dividing the first operand (operand1) by the second operand (operand2).

Note that division by zero is not an error. The result of division by zero is Infinity.

##### % operator

`operand1 % operand2`

This operator returns the integer remainder (which may be 0) from the division of operand1 by operand2.

#### String Operators

These operators provide string functions using operators. Many other string functions are available, see String.

##### + string operator

`str1 + str2`

This operator returns a string that is the concatenation of its operands, (str1 and str2).

See also + operator.

##### += string operator

`str1 += str2`

This operator appends its second operand (str2) onto the end of the first operand (str1).

See also += operator.

#### Logical Operators

These operators are used to evaluate whether their operands are `true` or `false` in terms of the operator (for unary operators) and in terms of each other (for binary operators).

The binary operators use short-circuit logic, i.e. they do not evaluate their second operand if the logical value of the expression can be determined by evaluating the first operand alone.

##### && operator

`operand1 && operand2`

This operator returns an object whose value is `true` if both its operands are `true`; otherwise it returns an object whose value is false.

Specifically, if the value of operand1 is `false`, the operator returns operand1 as its result. If operand1 is `true`, the operator returns operand2.

##### || operator

`operand1 || operand2`

This operator returns an object whose value is `true` if either of its operands are `true`; otherwise it returns an object whose value is false.

Specifically, if the value of operand1 is `true`, the operator returns operand1 as its result. If operand1 is `false`, the operator returns operand2.

##### ! operator

`! operand`

If the operand's value is `true`, this operator returns `false`; otherwise it returns `true`.

#### Comparison Operators

These operators are used to compare objects and their values.

##### == operator

`operand1 == operand2`

Returns `true` if the operands are equal; otherwise returns `false`.

##### != operator

`operand1 != operand2`

Returns `true` if the operands are not equal; otherwise returns `false`.

##### === operator

`operand1 === operand2`

Returns `true` if the operands are equal and of the same type; otherwise returns `false`.

##### !== operator

`operand1 !== operand2`

Returns `true` if the operands are not equal or if the operands are of different types; otherwise returns `false`.

##### > operator

`operand1 > operand2`

Returns `true` if operand1 is greater than operand2; otherwise returns `false`.

##### >= operator

`operand1 >= operand2`

Returns `true` if operand1 is greater than or equal to operand2; otherwise returns `false`.

##### < operator

`operand1 < operand2`

Returns `true` if operand1 is less than operand2; otherwise returns `false`.

##### <= operator

`operand1 <= operand2`

Returns `true` if operand1 is less than or equal to operand2; otherwise returns `false`.

#### Bit-wise operators

##### & operator

`operand1 & operand2`

Returns the result of a bit-wise AND on the operands (operand1 and operand2).

##### ^ operator

`operand1 ^ operand2`

Returns the result of a bit-wise XOR on the operands (operand1 and operand2).

##### | operator

`operand1 | operand2`

Returns the result of a bit-wise OR on the operands (operand1 and operand2).

##### ~ operator

`~ operand`

Returns the bit-wise NOT of the operand.

##### << operator

`operand1 << operand2`

Returns the result of a bit-wise left shift of operand1 by the number of bits specified by operand2. Zeros are shifted in from the right.

##### >> operator

`operand1 >> operand2`

Returns the result of a bit-wise (sign propagating) right shift of operand1 by the number of bits specified by operand2.

##### >>> operator

`operand1 >>> operand2`

Returns the result of a bit-wise (zero filling) right shift of operand1 by the number of bits specified by operand2. Zeros are shifted in from the left.

#### Special Operators

##### ?: operator

`expression ? resultIfTrue : resultIfFalse`

This operator evaluates its first operand, the expression. If the expression is `true`, the value of the second operand (resultIfTrue) is returned; otherwise the value of the third operand (resultIfFalse) is returned.

##### , operator

`expression1, expression2`

This operator evaluates its first and second operand (expression1 and expression2), and returns the value of the second operand (expression2).

The comma operator can be subtle, and is best reserved only for use in argument lists.

##### function operator

         var variable = function( optArguments ) { Statements }

This operator is used to create anonymous functions. Once assigned, the variable is used like any other function name, e.g. `variable(1, 2, 3)`. Specify the argument names (in optArguments) if named arguments are required. If no optArguments are specified, arguments may still be passed and will be available using the arguments list.

The Qt Script function operator supports closures, for example:

            function make_counter( initialValue )
            {
                var current = initialValue;
                return function( increment ) { current += increment; return current; }
            }
            // ...
            var counterA = make_counter( 3 );  // Start at 3.
            var counterB = make_counter( 12 ); // Start at 12.
            debug( counterA( 2 ) );  // Adds 2, so prints 5
            debug( counterB( 2 ) );  // Adds 2, so prints 14
            debug( counterA( 7 ) );  // Adds 7, so prints 12
            debug( counterB( 30 ) ); // Adds 30, so prints 44

Note that for each call to make_counter(), the anonymous function that is returned has its own copy of current (initialized to the initialValue), which is incremented independently of any other anonymous function's current. It is this capturing of context that makes the function that is returned a closure.

See also function and Function type.

##### in operator

`property in Object`

Returns `true` if the given Object has the given property; otherwise returns `false`.

##### instanceof operator

`object instanceof type`

Returns `true` if the given object is an instance of the given type, (or of one of its base classes); otherwise returns `false`.

##### new operator

`var instance = new Type( optArguments );`

This function calls the constructor for the given Type, passing it the optional arguments (optArguments) if any, and returns an instance of the given Type. The Type may be one of the built-in types, one of the library types, or a user-defined type.

Example:

            var circle = new Circle( x, y );
            var file = new File();

##### this operator

`this.property`

The this operator may only be used within a function that is defined within a class or form, i.e. a member function. Within the scope of the function this is a reference to the particular instance (object) of the class's type.

Example:

            class MinMax {
                var _min;
                var _max;
                function MinMax( min, max ) { this._min = min; this._max = max; }
                function max() { return this._max; }
                function min() { return this._min; }
                function setMax( value ) { this._max = value; }
                function setMin( value ) { this._min = value; }
            }

##### typeof operator

`typeof item`

This operator returns a type of the object as a string.

Example:

            var f = new Function("arguments[0]*2"); // "object"
            var str = "text"; // "string"
            var pi = Math.PI; // "number"

Functions and built-in objects have a `typeof` of "function".

### Declarations

Classes, functions, variables and constants are declared with class, function, var and const respectively.

#### class

        class ClassName {
            static var ClassVariable;
            var MemberVariable;
            static function ClassFunction { Statements; }
            function ClassName() { Statements; } // constructor
            function MemberFunction() { Statements; }
        }

This keyword is used to define new classes. After the keyword `class` comes the ClassName, then optionally, the keyword `extends` followed by a class name from which this class derives, then an opening brace. Class variables are declared with `static` var (ClassVariable). Only one instance of these variables exists per class. Member variables (MemberVariable), are declared with var; each instance (object) of the class has its own copy of each member variable. Functions declared with the keywords `static` function are class functions (ClassFunction); these functions are called using the name of the class rather than from an object. In the standard library, the Math functions are all static, for example Math.sin(). Member functions (methods) are called by objects and are declared with function. The constructor is the member function with the same name as the class; constructors must not contain an explicit return statement, or have an explicit return type, since Qt Script for Application handles these automatically.

A class that only contains `static` const, var and function definitions does not need a constructor.

Example:

            class Area {
                static var count = 0;
                var _name;
                function Area( name ) { this._name = name; this.count++ }
                function destroy() { this.count--; }
                static function count() { return this.count; }
                function name() { return this._name; }
                function setName( name ) { this._name = name; }
            }

In this example we define the "Area" class. When an instance of the class is constructed:

            var area = new Area( "Berkshire" );

the given name is assigned to the object's `_name` variable, and the class's `static` `count` is incremented. The destroy() function is not called automatically; it must be called explicitly if there is any clean-up to do.

All the class's variables and functions must be defined within the class definition. ECMAScript does not have destructors. But for Qt Script for Application forms, Qt Script for Application will call a class's destroy() function, if it has one, before deleting the form. This occurs because Qt Script for Application automatically connects the form's destroyed() signal to the destroy() function. If you want a destructor you must create your own and call it explicitly.

Classes are all derived from Object. It is possible to derive a class from another class using the `extends` keyword, for example:

            class City extends Area {
                var _population;
                function City( name, population )
                {
                    Area( name );
                    _population = population;
                }
                function population() { return _population; }
                function setPopulation( population ) { _population = population; }
            }

See also function.

#### const

`const identifier = Value;`

This keyword is used to define constant values. The identifier is created as a constant with the given Value. The constant is global unless defined within the scope of a class or function.

Example:

            const PI2 = Math.PI * 2;
            const COPYRIGHT = "Copyright (c) 2001";

Attempts to assign to a constant cause the interpreter to issue an error message and stop.

#### function

        function functionName( arguments )
        {
            Statements;
        }

Functions may also be declared within the scope of a class definition. In this situation, the functions become member functions (methods) of the class that contains them. See class.

#### var

        var variableName;
        var anotherVariableName = InitialValue;

This keyword is used to declare and optionally initialize variables. If just the variableName is given, the variable is created, but it has no value, i.e. its value is undefined. If an InitialValue is given, the variable is created and assigned this InitialValue. Variables declared within functions are local to the function in which they are declared. Variables declared outside of functions and classes are global.

Example:

            var i;
            var count = 22;
            var str = "string";

## Control Statements

The flow--of--control in Qt Script programs is controlled by control statements, for example, if and switch, for and while. Qt Script also supports exceptions with try and catch.

### break

        label:
        for ( var i = 0; i < limit; i++ ) {
            if ( condition ) {
                break label;
            }
        }

        switch ( expression ) {
            case 1:
                Statements1;
                break;
            default:
                DefaultStatements;
                break;
        }

This keyword is used in for loops, do loops, while loops and switch statements. When a `break` statement is encountered in a loop, control is passed to the statement following the end of the inner-most loop that contains the `break` statement; unless the `break` statement is followed by the name of a label, in which case control passes to the statement governed by the label.

A `break` statement is usually placed at the end of each case in a switch statement to prevent the interpreter "falling through" to the next case. When the interpreter encounters a `break` statement, it passes control to the statement that follows the inner-most enclosing `switch` statement. If every `case` has a corresponding `break`, then at most one `case`'s statements will be executed. If the `break` statement is followed by a label name (label) then when the `break` is encountered, control will pass to the statement marked with that label; this is useful, for example, for breaking out of deeply nested loops.

Example:

            red:
            for ( x = 0; x < object.width; x++ ) {
                for ( y = 0; y < object.height; y++ ) {
                    if ( color[x][y] == 0xFF0000 ) {
                        break red;
                    }
                }
            }

See switch for another example. See also do, while, for and break.

### case

        switch ( expression ) {
            case Value:
                Statements;
                break;
            default:
                DefaultStatements;
                break;
        }

This keyword is used in switch statements. For each possible value that a `switch` statement's expression may evaluate to, one `case` may be written, (but see default.) If a case's literal value (Value) matches the value of the `switch` statement's expression, then that `case`'s statements (Statements) are executed.

Normally a `case`'s statements are terminated by a break statement which causes execution to pass to the end of the `switch` statement.

See switch for an example.

### catch

        try {
            Statements;
        }
        catch( exception ) {
            ExceptionStatements;
        }

This keyword is used in try statements. If an exception occurs, then the ExceptionStatements in a matching `catch` block are executed.

Catch blocks come in two varieties, unqualified and qualified. An unqualified `catch` block has the form:

            catch ( e ) {
                /* statements */
            }

and a qualified `catch` block has the form:

            catch ( e if e instanceOf RangeError ) {
                /* statements */
            }

The possible exception types are:

EvalError -- the result of a failed eval() call. RangeError -- a result that is out of range, e.g. an array index to an element that isn't in the array. TypeError -- an attempt to perform an operation on an object of an inappropriate type. User defined exceptions -- exceptions that are objects of a user-defined type.

See try for an example.

### continue

        for ( var i = 0; i < limit; i++ ) {
            if ( condition ) {
                continue;
            }
            Statements;
        }

This keyword is used within the context of a for, while or do loop.

If a `continue` statement is encountered in a for loop, execution immediately passes to the third part of the for loop (normally where a counter is incremented or decremented), and then execution continues normally, i.e. the middle part of the for loop (the conditional) is tested, and if true, the body of the loop is executed.

If a `continue` statement is encountered in a while or do loop, execution immediately passes to the conditional, which is retested; the body of the loop will be executed if the conditional is still true.

See do for an example. See also do, while, for and break.

### default

        switch ( expression ) {
            case 1 :
                Statements1;
                break;
            default :
                DefaultStatements;
                break;
        }

This keyword is used in switch statements. It is used instead of case to match anything that the `switch` statement's expression has evaluated to. If no `default` is used, and none of the cases match, then the `switch` statement will not execute anything and control will pass on to the following statement. If `default` is used, it must be the last case in the `switch` statement. This is because each `case` is evaluated in order, and since `default` matches any value, it will always be executed if the interpreter reaches it, and any following cases would always be ignored. When the `default` case is encountered its DefaultStatements are executed. It is customary to end a `default` statement with a break.

See switch for an example.

### do

        do {
            Statements;
        } while ( condition );

This keyword is used in conjunction with while to form a loop which is guaranteed to execute at least once.

The Statements in the braces following the `do` are executed once. If the while condition evaluates to `true`, execution passes back to the `do`, and the whole process repeats. If the while loop's conditional ever becomes `false`, execution continues from the statement following the while statement.

Example:

            var x = 0;
            do {
                x += 5;
                if ( x == 50 )
                    continue;
                System.println( x );
            } while ( x < 100 );

The example prints 5, 10, 15, ..., 45, 55, 60, 65, ..., 95 on the console.

See also while, for, continue and break.

### else

        if ( condition ) {
            Statements;
        }
        else {
            ElseStatements;
        }

The `else` keyword is used in conjunction with if. See if for details.

### for

        for ( i = 0; i < limit; i++ ) {
            Statements;
        }

This keyword is used to create a loop that executes a fixed number of times.

The `for` statement is broken into parts as follows: the keyword `for`, an opening parentheses, zero or more statements (the first part), a semi-colon, a conditional expression (the second part), a semi-colon, zero or more statements (the third part), a closing parentheses, and finally a statement or block that is governed by the `for` loop.

The first part of the `for` statement is typically used to initialize (and possibly declare) the variable used in the conditional in the second part of the `for` loop statement. This part is executed once before the loop begins. This part may be empty.

The second part contains a conditional expression. The expression is evaluated before each iteration of the loop (including before the first iteration). If this expression evaluates to `false`, the statement or block governed by the `for` loop is not executed and control passes to the statement that follows. If the condition is never `true`, the statement or block governed by the `for` loop will never be executed. If the condition expression is `true`, the statement or block governed by the `for` loop is executed, and then the third part of the `for` statement is executed, before control is passed back to the conditional expression with the whole process being repeated. This part should not be empty.

The third part contains statements which must be executed at the end of every iteration of the loop. This part is typically used to increment a variable that was initialized in the first part, and whose value is tested in the second part. This part may be empty.

Example:

            var a = [ "a", "b", "c", "d", "e" ];
            for( var i = 0; i < a.length; i++ ) {
                System.println( a[ i ] );
            }

See also do, while, continue and break.

### if

        if ( expression1 ) {
            // statements1
        else {
            // elsestatements
        }

        if ( expression1 ) {
            // statements1
        else if ( expression2 ) {
            // statements2
        }
        // else if ...
        else {
            // elsestatementsN
        }

An `if` statement provides a two-way branch. A multi-way branch is achieved using `else if`s. (See also switch.)

If the first expression, expression1, is `true`, then the statements governed by that expression (statements1) will be executed, after which control will pass to the statement following the `if` block.

If expression1 is `false`, control passes to the `else` statement. If the `else` has no following `if`, the `else` statements (elsestatements) are executed, after which control will pass to the statement following the `if` block. If the `else` has a following `if`, then step 1 or step 2 (this step) is repeated for that `if` statement depending on whether its expression is `true` or `false`.

### finally

        try {
            Statements;
        }
        finally {
            finalStatements;
        }

A `finally` block is a block of code that is executed after the governing try block. If no exceptions occur within the try block, control will pass to the `finally` block after the last statement in the try block has been executed. If an exception occurs within the try block, control is passed immediately to the `finally` block.

See also try.

### label

`labelname: Statement;`

Statements may be labelled; the syntax is labelname followed by a colon, followed by the Statement. The labelname is any valid (unique) identifier.

See break for an example.

### return

`return optExpression;`

A `return` statement may occur anywhere within a function, including member functions, but not within constructors. When a `return` statement is encountered, control leaves the function immediately, and execution resumes at the statement following the call that invoked the function. If the `return` statement is followed by an expression (optExpression) the value of the expression is returned to the caller.

Example:

            function inRange( v, min, max )
            {
                if ( v >= min && v <= max ) {
                    return true;
                }
                else {
                    return false;
                }
            }

### switch

        switch( expression ) {
            case Value :
                Statements;
                break;
            default :
                DefaultStatements;
                break;
        }

A `switch` statement provides a multi-way branch. The expression is evaluated once, then each case is checked in order to find one with a Value that matches the value of the expression. If a match is made, the Statements of the matching case are executed, after which control passes to the statement following the `switch` block. If no matching case is found, and there is a default case, the DefaultStatements are executed, after which control passes to the statement following the `switch` block. If there is no matching case and no default, no statements within the `switch` block are executed, and control passes to the statement following the `switch` block.

Note that if a default is used it must be come after all the cases; this is because once default is encountered it is treated as a matching case regardless of what follows.

Every case, and the default (if used) should have a break as their last statement. If break is not present, control will "drop through" to the following statements, which is not usually the desired behavior.

The expression may be any arbitrary Qt Script for Application expression that evaluates to an object that can be strictly compared. For example, an expression that evaluates to a Boolean, Date, Number or String value.

Example:

        switch( expr ) {
            case 1:
                doActionOne();
                break;
            case "two":
                doActionTwo();
                break;
            case 3:
                doActionThree();
            case 4:
                doActionFour();
                break;
            default:
                doDefaultAction();
                break;
        }

In the example, if `expr` has the value 1, the doActionOne() function will be called. But if `expr` has the value 3, both doActionThree() and doActionFour() will be called, because case 3 doesn't have a `break` statement, and execution "falls through" to case 4. If `expr` is not 1, "two", 3 or 4 then the default case will be matched and doDefaultAction() will be executed.

See also break.

### throw

        try {
            Statements;
            throw "an exception";
        }
        catch ( e ) {
            if ( e == "an exception" ) {
                ExceptionStatements;
            }
            else {
                OtherExceptionStatements
            }
        }

The `throw` keyword is used to raise user-defined exceptions.

Example:

            function monthToName( i )
            {
                var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

                if ( i < 0 || i > 11 ) {
                    throw "month number out of range";
                }
                else {
                    return IndexToMonth[ i ];
                }
            }

It is also possible to define a user-defined exception class and throw an object of that type, e.g.

            throw new AUserDefinedException( "month number out of range" );

See also try.

### try

        try {
            Statements;
        }
        catch ( e ) {
        }

        try {
            Statements;
        }
        finally {
        }

The `try` keyword is used to identify a statement block for which exceptions will be caught. There are two kinds of `try` block, `try...catch` and `try...finally`.

try...catch

If an exception occurs within a `try...catch` block, control is passed to the first catch block. If that `catch` block does not accept the exception, control is passed on to the next `catch` block (if any), and so on, until there are no more `catch` blocks, in which case the exception is passed up the call chain until an enclosing `catch` block is found to accept it, or if none accept it, the program will terminate.

Catch blocks come in two varieties, unqualified and qualified. An unqualified `catch` block has the form:

            catch ( e ) { /* statements */ }

and a qualified `catch` block has the form:

            catch ( e if e instanceOf RangeError ) { /* statements */ }

See catch for details of the qualifiers.

try...finally

If an exception occurs within a `try...catch` block, control is passed to the finally block. This is useful if you want to ensure that something happens at the end of the block, no matter what.

Examples:

            try {
                file = new File;
                file.open( filename );
                process( file );
            }
            finally {
                file.close();
            }

In this example, the file is always closed, even if an exception occurred.

            try {
                var a = monthToName( 11 );
                var b = monthToName( 2 );
            }
            catch ( e ) {
                if ( e == "month number out of range" ) {
                    debug( "Code error: " + e );
                }
                else {
                    throw e;
                }
            }

In this example, the monthToName() function is called to set two variables. If the function fails, it throws an exception rather than returns an error value, so no explicit check for an error value is necessary. If one of the function calls failed debug() is called; otherwise the exception is re-thrown so that it can be handled at a higher level. (See throw for the definition of monthToName().)

### while

        while ( condition ) {
            Statements;
        }

This keyword is used to repeat a block of code zero or more times. When the `while` statement is encountered the condition is evaluated. If the condition is `true`, the Statements in the `while` block are executed; otherwise control passes to the statement following the `while` block. If the condition is `true`, after the Statements have been executed, the condition is again evaluated, and the whole process repeats.

Example:

            var i = 10;
            while ( i > 0 ) {
                debug( i );
                i--;
            }

See also do, for, continue and break.

### with

        with ( QualifyingName ) {
            Statements;
        }

This keyword is used to indicate that any unqualified names in the Statements should be qualified by QualifyingName.

Example:

        // Without with
            System.print "one ";
            System.print "two ";
            System.println "three";
        // With with
            with ( System ) {
                print "one ";
                print "two ";
                println "three";
            }

If multiple qualifying names are required, with statements can be nested, e.g.

            with ( System ) {
                with ( Math ) {
                    print abs( -4 );
                    print pow( 2, 3 );
                    print random();
                }
            }

Forcing the interpreter to do the lookup may be slower than using the fully qualified names.