Home · All Classes · All Functions · Overviews

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 implicitly in QML whenever a property is assigned an JavaScript expression. The following QML uses two property bindings to connect the size of the rectangle to that of otherItem.

 Rectangle {
     width: otherItem.width
     height: otherItem.height
 }

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 builtin JavaScript objects like Date and Math. Assigning a constant value to a property can even be thought of as a binding - afterall, a constant is a valid JavaScript expression! Here are some examples of more complex bindings:

 Rectangle {
     Script {
         function calculateMyHeight() {
             return Math.max(otherItem.height, thirdItem.height);
         }
     }

     anchors.centerIn: parent
     width: Math.min(otherItem.width, 10)
     height: calculateMyHeight()
     color: { if (width > 10) "blue"; else "red" }
 }

Being JavaScript expressions, bindings are evaluated in a scope chain. The QML Scope documentation covers the specifics of scoping in QML.

Binding Element

The implicit binding syntax shown previously is easy to use and works perfectly for most uses of bindings. In some advanced cases, it is necessary to create bindings explicitly using the Binding element.

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

 Binding {
     target: system
     property: "brightness"
     value: slider.value
 }


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