Data Binding in Qt and WP7
This article demonstrates how to work with Data Binding in Qt and WP7. See QML Property Binding and Data Binding (MSDN) for a more detailed overview.
See Also
- QML Property Binding
- Data Binding (MSDN)
- Data Binding to Controls QuickStart (Windows Phone Dev Center)
Article Metadata
Code Example
Tested with
Compatibility
Article
Contents |
Introduction
Data binding is a technique that binds two data/information sources together and maintains synchronization of data. In both Qt and Windows Phone data binding is used to synchronise UI components to each other and to the application engine/business logic.
In this simple example we create two controls, one for text entry and the other for displaying the entered text. Data binding is used to ensure that the content of the controls is synchronised. Screenshots of both apps are shown below.
Implementation
Qt Project (main.qml)
Data binding between QML objects in the same file is trivially easy: simply assign the property of source object into the target object property.
So for example, we create a source TextField (id:sourceTextField) and a target Text QML Element (id:targetText).
TextField {
id: sourceTextField;
y:160
width: parent.width -80
text: "Enter Text Here"
errorHighlight: true
anchors.horizontalCenter: parent.horizontalCenter
}
//The target text element
Text {
id:targetText
text: sourceTextField.text //Data binding!
font.pixelSize: 25
font.bold: true
y:330
x:50
color: "green"
}
To bind the source and target, we assign sourceTextField's text property to targetText's text property.
...
id:targetText
text: sourceTextField.text //Data binding!
...
Sometimes we need to bind to a property of an object that wasn't directly instantiated by QML - generally a property of a class exported to QML by C++. In this case you can use the QML Binding Element to bind any element to any value:
Binding { target: targetText; property: "text"; value: sourceTextField.text }
WP7 Project (MainPage.xaml)
The Windows Phone example is very similar. We create a TextBox for text entry and a TextBlock for displaying the entered data.
<TextBox Height="72" HorizontalAlignment="Left" Margin="35,191,0,0"
Name="sourceTextBox" Text="TextBox" VerticalAlignment="Top" Width="381" />
<TextBlock Foreground="Green" FontStyle="Italic" FontFamily="Times New Roman" FontSize="35" Height="63" HorizontalAlignment="Left" Margin="50,367,0,0"
Name="targetTextBlock" Text="{Binding Text, ElementName=sourceTextBox}" VerticalAlignment="Top" Width="350" />
The data binding is declared in the targetTextBlock using the Binding syntax:
Text="{Binding Text, ElementName=sourceTextBox}Source Code
- The full source code of Qt example is available here: File:BindingQt.zip
- The full source code of WP7 example is available here: File:BindingWP7.zip


(no comments yet)