Property Binding


QML components have properties that can be read and modified by other objects. In QML, properties serve many purposes but their main function is to bind to values. Values may be a basic type, or other QML elements.

The syntax for properties is:

[default] property <type> <name>[: defaultValue]

Elements already possess useful properties but, to create custom properties, precede the property name with the keyword property.

  1.                 Rectangle  {
  2. width: 320; height: 240
  3. color: "lightblue"
  4. focus: true
  5. property int counter
  6. property real area: 100.45
  7. }

QML property rules coincide with many of JavaScript's property rules, for example, property names must begin with a lowercase letter. JavaScript reserved words are not valid property names.

Property Binding

Property binding is a declarative way of specifying the value of a property. Binding allows a property's value to be expressed as an JavaScript expression that defines the value relative to other property values or data accessible in the application. The property value is automatically kept up to date if the other properties or data values change.

Property bindings are created in QML using the colon ":" before the value:

  1.                 Rectangle  {
  2.     width: parent.width
  3. }

The property binding causes the width of the Rectangle to update whenever the parent's width changes.

QML extends a standards compliant JavaScript engine, so any valid JavaScript expression can be used as a property binding. Bindings can access object properties, make function calls and even use built-in JavaScript objects such as Date and Math.

  1. function calculateArea(width, height)  {
  2.     return (width * height) * 0.5
  3. }
  5. Rectangle  {
  6.     width: 150; height: 75
  7.     property real area: calculateArea(width, height)
  8.     property real parentArea: calculateArea(parent.width,parent.height)
  9.     color:  { if (area > parentArea) "blue"; else "red" }
  10. }

While syntactically bindings can be of arbitrary complexity, if a binding starts to become overly complex - such as involving multiple lines, or imperative loops - it may be better to refactor the component entirely, or at least factor the binding out into a separate function.

Property Assignment versus Property Binding

When working with both QML and JavaScript, it is important to differentiate between QML property binding and JavaScript value assignment. In QML, a property binding is created using the colon ":".

  1.                 Rectangle  {
  2.     width: parent.width
  3. }

The property binding causes the width of the Rectangle to update whenever the parent's width changes.

Assigning a property value (using the equals sign "=") does not create a property binding.

  1.                 Rectangle  {
  2.     Component.onCompleted:  {
  3.         width = 150
  4.     }
  5. }

Instead of creating a property binding, the assignment simply sets the Rectangle width value to a number when the Component.onCompleted code is invoked.

Assigning a value to a property that is already bound will remove the previous binding. A property can only have one value at a time (a list of property is one value), and if any code explicitly re-sets this value, the property binding is removed.

There is no way to create a property binding directly from imperative JavaScript code, although it is possible to use the Binding element.

Types of Properties

Properties may bind to different types, but they are are type-safe. That is, properties only allow you to assign a value that matches the property type. For example, if a property is a real, and if you try to assign a string to it you will get an error.

  1. property real volume: "four"  //generates an error

Certain properties bind to more complex types such as other elements and objects.

Basic Property Types

Basic types such as int, real, and other Qt structures may be bound to properties. For a list of types, visit the QML Basic Types document.

The id Property

Each QML object may be given a special unique property called an id. No other object within the same QML component (see QML Documents) can have the same id value. QML objects may then access an object using the id property.

  1.                 Rectangle  {
  2.     id: container
  3.     width: 100; height: 100
  4.     Rectangle  {
  5.         width: parent.width; height: parent.height
  6.     }
  7. }
  8. Rectangle  {
  9.     width: container.width; height: container.height
  10. }

A component may readily access its parent's properties by using the parent property.

Note that an id must begin with a lower-case letter or an underscore. The id cannot contain characters other than letters, numbers, underscores, and JavaScript reserved words.

Elements and Objects as Property Values

Many properties bind to objects. For example, the Item element has a states property that can bind to State elements. This type of property binding allows elements to carry additional non-children elements. Item's transitions property behaves in a similar way; it can bind to Transition elements.

Care must be taken when referring to the parent of an object property binding. Elements and components that are bound to properties are not necessarily set as children of the properties' component.

  1.                 Rectangle  {
  3.     id: parentrectangle
  4.     gradient:
  5.         Gradient  { //not a child of parentrectangle
  7.             //generates a TypeError
  8.             //Component.onCompleted: console.log(parent.width)
  9.         }
  11.     //child of parentrectangle
  12.     Rectangle  {property string name: "childrectangle"}
  14.     //prints "childrectangle"
  15.     Component.onCompleted: console.log(children[0].name)
  16. }

The code snippet has a Gradient element that attempts to print its parent's width value. However, the Gradient element is bound to the gradient property, not the children property of the Rectangle. As a result, the Gradient does not have the Rectangle as its parent. Printing the value of parent.width generates an error. Printing the Rectangle object's first child's name will print childrectangle because the second Rectangle is bound to the children property.

For more information about the children property, please read the Default Properties section.

Attached Properties

Certain objects provide additional properties by attaching properties to other objects. For example, the Keys element have properties that can attach to other QML objects to provide keyboard handling.

  1.                 Component  {
  2.     id: listdelegate
  3.     Text  {
  4.         text: "Hello"
  5.         color: ListView.isCurrentItem ? "red" : "blue"
  6.     }
  7. }
  8. ListView  {
  9.     delegate: listdelegate
  10. }

The element ListView provides the delegate, listdelegate, the property isCurrentItem as an attached property. The ListView.isCurrentItem attached property provides highlight information to the delegate. Effectively, the ListView element attaches the ListView.isCurrentItem property to each delegate it creates.

Attached Signal Handlers

Attached signal handlers are similar to attached properties in that they attach to objects to provide additional functionality to objects. Two prominent elements, Component and Keys element provide signal handlers as attached signal handlers.

  1.                 Item  {
  2.     Keys.onPressed: console.log("Key Press Detected")
  3.     Component.onCompleted: console.log("Completed initialization")
  4. }

Read the QML Signal and Handler Event System and the Keyboard Focus in QML articles for more information.

List properties

Some properties may accept a binding to a list property, where more than one component can bind to the property. List properties allow multiple States, Gradients, and other components to bind to a single property.

  1.                 Item  {
  2.     id: multistate
  3.     states: [
  4.         State  {name: "FETCH"},
  5.         State  {name: "DECODE"},
  6.         State  {name: "EXECUTE"}
  7.     ]
  8. }

The list is enclosed in square brackets, with a comma separating the list elements. In cases where you are only assigning a single item to a list, you may omit the square brackets.

  1.                 Item  {
  2.     id: monostate
  3.     states: State  {name: "RUNNING"}
  4. }

To access the list, use the index property.

  1.     Component.onCompleted: console.log (multistate.states[0].name)

The snippet code simply prints the name of the first state, FETCH.

See the list type documentation for more details about list properties and their available operations.

Grouped Properties

In some cases properties form a logical group and use either the dot notation or group notation.

Grouped properties may be written both ways:

  1.                 Text  {
  2.     //dot notation
  3.     font.pixelSize: 12
  4.     font.bold: true
  5. }
  7. Text  {
  8.     //group notation
  9.     font  {pixelSize: 12; bold: true}
  10. }

In the element documentation grouped properties are shown using the dot notation.

Property Aliases

Unlike a property definition, which allocates a new, unique storage space for the property, a property alias connects the newly declared property, called the aliasing property as a direct reference to an existing property, the aliased property. Read or write operations on the aliasing property results in a read or write operations on the aliased property, respectively.

A property alias declaration is similar to an ordinary property definition:

[default] property alias <name>: <alias reference>

As the aliasing property has the same type as the aliased property, an explicit type is omitted, and the special alias keyword is before the property name. Instead of a default value, a property alias has a compulsory alias reference. Accessing the aliasing property is similar to accessing a regular property. In addition, the optional default keyword indicates that the aliasing property is a default property.

  1. property alias buttonLabel: label.text
  2. Text  {
  3.     id: label
  4.     text: "empty label"
  5. }

When importing the component as a Button, the buttonlabel is directly accessible through the label property.

  1. Button  {
  2.     id: textbutton
  3.     buttonLabel: "Click Me!"
  4. }

In addition, the id property may also be aliased and referred outside the component.

  1.                 Rectangle  {
  2.     property alias buttonImage: image
  4.     Image  {id: image}
  5. }

The imagebutton component has the ability to modify the child Image object and its properties.

  1. Button  {
  2.     id: imagebutton
  3.     buttonImage.source: ""
  4.     buttonLabel: buttonImage.source
  5. }

Using aliases, properties may be exposed to the top level component. Exposing properties to the top-level component allows components to have interfaces similar to Qt widgets.

Considerations for property aliases

Aliases are only activated once the component completes its initialization. An error is generated when an uninitialized alias is referenced. Likewise, aliasing an aliasing property will also result in an error.

  1. property alias widgetLabel: label
  3. //will generate an error
  4. //widgetLabel.text: "Initial text"
  6. //will generate an error
  7. //property alias widgetLabelText: widgetLabel.text
  9. Component.onCompleted: widgetLabel.text = "Alias completed Initialization"

When importing the component, however, aliasing properties appear as regular Qt properties and consequently can be used in alias references.

It is possible for an aliasing property to have the same name as an existing property, effectively overwriting the existing property. For example, the following component has a color alias property, named the same as the built-in Rectangle::color property:

  1.                 Rectangle  {
  2.     id: coloredrectangle
  3.     property alias color: bluerectangle.color
  4.     color: "red"
  6.     Rectangle  {
  7.         id: bluerectangle
  8.         color: "#1234ff"
  9.     }
  11.     Component.onCompleted:  {
  12.         console.log (coloredrectangle.color)    //prints "#1234ff"
  13.         setInternalColor()
  14.         console.log (coloredrectangle.color)    //prints "#111111"
  15.         coloredrectangle.color = "#884646"
  16.         console.log (coloredrectangle.color)    //prints #884646
  17.     }
  19.     //internal function that has access to internal properties
  20.     function setInternalColor()  {
  21.         color = "#111111"
  22.     }
  23. }

Any object that use this component and refer to its color property will be referring to the alias rather than the ordinary Rectangle::color property. Internally, however, the coloredrectangle can correctly set its color property and refer to the actual defined property rather than the alias.

The TabWidget example uses aliases to reassign children to the ListView, creating a tab effect.

Default Properties

When imported, QML components will bind declared children to their designated default properties. The optional default attribute specifies a property as the default property. For example, the State element's default property is its changes property. PropertyChanges elements may simply be placed as the State's children and they will be bound to the changes property.

  1.                 State  {
  2.     changes: [
  3.         PropertyChanges  {},
  4.         PropertyChanges  {}
  5.     ]
  6. }
  8. State  {
  9.     PropertyChanges  {}
  10.     PropertyChanges  {}
  11. }

Similarly, the Item element's default property is its data property. The data property manages Item's children and resources properties. This way, different data types may be placed as direct children of the Item.

  1.                 Item  {
  2.     Text  {}
  3.     Rectangle  {}
  4.     Timer  {}
  5. }
  7. Item  {
  8.     //without default property
  9.     children: [
  10.         Text  {},
  11.         Rectangle  {}
  12.     ]
  13.     resources: [
  14.         Timer  {}
  15.     ]
  16. }

Reassigning a default property is useful when a component is reused. For example, the TabWidget example uses the default attribute to reassign children to the ListView, creating a tab effect.

Using the Binding Element

In some advanced cases, it may be necessary to create bindings explicitly with theBinding element.

For example, to bind a property exposed from C++ (system.brightness) to a value written in QML (slider.value), you could use the Binding element as follows:

  1.                 Binding  {
  2.     target: system
  3.     property: "brightness"
  4.     value: slider.value
  5. }

Changing Property Values in States

The PropertyChanges element is for setting property bindings within a State element to set a property binding.

  1.                 Rectangle  {
  2.     id: rectangle
  4.     states: State  {
  5.         name: "WARNING"
  6.         PropertyChanges  {
  7.             target: rectangle
  8.             color: warning.color
  9.         }
  10.     }
  11. }

The rectangle's color property will bind to the warning component's color property when its state is set to the WARNING state.

Notes provided by the Qt Community

No notes