Table of Content

Introduction to Qt Quick

Today’s consumers and enterprise users are tough to please. They grew up using slick UIs on their game consoles and seeing even fancier UIs at the movies. Specifications and feature lists alone are no longer selling points; they are means to an end. Visual impact and experience WOW are the selling points that matter today, and the consumer expects this visual delight whether they are using a powerful corporate notebook computer, a mobile device, a sleek tablet, or a set-top box.

Delivering this experience requires designers and developers to work together like never before. Gone are the days where designers could throw pixel maps over the wall and expect developers to implement their vision. So too are the days when developers could code purely for performance without regard to visual appeal. Design/development/test must become an iterative cycle, not a linear path. The Qt framework is known for high runtime performance and small footprint, making it ideal for mobile, embedded, and netbook applications. The Qt 4.7 release extends Qt with QML, a declarative language that codes the way designers think, and Qt Quick elements that are the building blocks for applications, Each frame of a story board is declared as a branch in an element tree; each visual aspect of a frame is declared as a property of elements on the branch; each transition between frames can be decorated with a variety of animations and effects.

The Qt Quick runtime implements the UI and provides direct access to native APIs and performance boosts with C++ extensions where appropriate. And because the runtime is implemented in Qt, it delivers cross-platform reach and flexibility.

Qt Creator, a development environment built for collaboration between designers and developers, supports Qt Quick. Designers work in a visual environment, developers work in a full-featured IDE, and Qt Creator supports round-trip iteration from design, to code, to test, and back to design.

Qt is built for the way product teams work today. Core business logic is coded by developers and optimized for performance, the interface is crafted by designers working with visual tools, and integrated tooling supports round-trip iteration between the disciplines.

Overview

Qt’s new user interface technology consists of the QML language, Elements that provide basic building blocks of the language, the QtDeclarative (C++) module that provides a runtime for the QML language, and a scripting language based on JavaScript that allows developers to implement logic in their projects with no C++ coding required. This technology set is supported by the Qt Creator tool that now includes a visual designer and other extensions to support creating, testing, debugging, and optimizing projects.

QML provides mechanisms to declaratively build an object tree using elements. QML improves the integration between JavaScript and Qt’s existing QObject based type system, adds support for automatic property bindings and provides network transparency at the language level.
Elements are a sophisticated set of graphical and behavioral building blocks. There are currently over 80 elements in the language, including visual elements such Rectangle, Gradient, and AnimatedImage; interaction elements including MouseArea and Flickable; state elements including PropertyChanges and StateChangeScript; and transition elements including Transition and SequentialAnimation. There are also elements to handle data, views, position, and other sophisticated aspects of building fluid UIs without C++ code.

Elements are combined together in QML documents to build components ranging in complexity from simple buttons and sliders, to complete internet-enabled applications like a Flickr photo browser. Developers and designers are free to build their own or choose from libraries of pre-built components.

Qt Quick builds on Qt’s existing strengths. QML can be used to incrementally extend an existing application or to build completely new applications. QML is fully extensible from C++.

A short introduction to QML

QML is a rich language, and a full treatment is beyond the scope of this paper. This paper will instead provide an introduction to what QML can do and how to integrate QML with C++ to get the best of both worlds: high-performance business logic built in C++ and highly dynamic user interfaces using QML. A full treatment of QML is available in the online documentation.

QML language

QML is a declarative language designed to describe the user interface of a program: both what it looks like, and how it behaves. In QML, a user interface is specified as a tree of objects with properties. JavaScript is used as a scripting language in QML.

Snippet 1 shows the basic QML syntax. The first statement imports the QtQuick module version 1.1 which implements the runtime environment in which the application will execute. To prevent elements introduced in later versions from affecting existing documents, the element types available within a document are controlled by the imported Modules. This versioning of QML allows developers to manage compatibility.

The snippet creates two objects: a Rectangle object and its child Image object. Objects are specified by their type, followed by a pair of braces in between which additional data can be defined for the object, such as its property values and any child objects.

Properties are specified with a property: value syntax. Notice the Image object has a property named source, which has been assigned the value “pics/logo.png”. The property and its value are separated by a colon.

Commenting in QML is similar to that used in C++

  • Single line comments start with // and finish at the end of the line.
  • Multiline comments start with /* and finish with */

  1. import QtQuick 1.1
  2.  
  3. Rectangle {
  4.     width: 200 // this is an inline comment
  5.     height: 200
  6.     color: "blue"
  7.     /*
  8.        And this is a
  9.        Multi-line comment.
  10.      */
  11.  
  12.     Image {
  13.         source: "pics/logo.png"
  14.         anchors.centerIn: parent
  15.     }
  16. }

Snippet 1: Basic QML syntax

Within objects, properties are bound to values using the property : expression statement. There are two aspects of this statement that bear explanation.

Firstly, expression is a JavaScript expression, which means you could set the properties based on a calculation, a condition, or other complex JavaScript manipulations.

You can use JavaScript expressions in most places where constants are allowed. For example, Snippet 2 binds the width and height of a rectangle to the result of a JavaScript expression. Admittedly this trivial expression is no more useful than the constants used in Snippet 1, but this same capability allows you to bind the width of the rectangle to some fraction of the width of a parent element.

Secondly, binding is different from assignment. In an assignment, the value of a property is set when the assignment statement is executed and is fixed thereafter until and unless the statement is executed again. In a binding, a property is set when the binding statement is first executed, but will change if and when the result of the expression used to set the property changes. (If desired, you could assign a value to the property using property = expression inside a JavaScript block.)

  • Tech note: Property binding is achieved by a NOTIFY signal being declared from within a Qt C++ object using the Q_PROPERTY() macro in a class that inherits QObject. If you do not know what that means, don’t worry. If you plan to build your application purely in QML, you do not need to know this as it is merely part of the plumbing that Qt Quick handles for you. If you plan to include some C++ in your application, the Qt C++ developers on the team will already know what this means.

  1. import QtQuick 1.1
  2.  
  3. Rectangle {
  4.     width: 2 * 100
  5.     height: 40 * 5
  6.     color: "blue"
  7.  
  8.     Image {
  9.         source: "pics/logo.png"
  10.         anchors.centerIn: parent
  11.     }
  12. }

Snippet 2: JavaScript expressions

The full QML language supports object identifiers, type-safe properties, signal handlers, and a lot of other details that we don’t want to distract you with here. When you are ready for that level of detail, check out the Introduction to the QML Language.

QML elements

Once you understand the basic underpinnings of the QML language, it’s time to dig into the real meat of the technology: Elements. An Element is a template for a basic building block out of which a QML program will be built. QML supports for example visual elements of types Rectangle and Text, interaction elements of type MouseArea and Flipable, and animation elements of type RotationAnimation and Transition. There are also complex element types that allow the developer to work with data, implement views in model-view architectures, and other housekeeping element types that will just add confusion at this point.

All elements include one or more properties (for example color) that can be controlled by the developer and many elements include signal handlers (for example onClicked) that can be used to react to events or changes in state.

Visual elements: Hello World

We have progressed quite far enough without presenting the obligatory Hello World example. Here is the code required to place the text Hello World! on top of a simple background rectangle:

  1. import QtQuick 1.1
  2.  
  3. Rectangle {
  4.     width: 300
  5.     height: 200
  6.     Text {
  7.         anchors.horizontalCenter: parent.horizontalCenter
  8.         anchors.verticalCenter: parent.verticalCenter
  9.         text: "Hello World"
  10.     }
  11. }

Snippet 3: Hello World

Let’s dissect this simple code. The Hello World example in Snippet 3 is a QML document, meaning it is a complete block of QML source code, ready to run. QML documents generally correspond to plain text files stored on a disk or network resource, but can also be constructed directly from text data.

A QML document always begins with one or more import statements. Here you see the import of Qt Quick 1.1.

Next you see the Rectangle element template used to create an active object. Objects can contain other objects, creating parent-child relationships. In the code above, the Rectangle object is parent to the Text object. The Rectangle element also defines a top-level window for managing the visual bounds and focus segmentation of the full UI.

Tech Note: The children property of elements contains a list of all visual children of the element; the resources property contains an equivalent list of all non-visual objects. Both lists are populated implicitly by default, or you can explicitly populate them if convenient. A third property, data, is a list containing objects in either the children or resources lists. You cannot explicitly populate the data property but it may be useful if you need to iterate through a list of visual and non-visual objects.

So you can write:

  1.  Item {
  2.      Text {}
  3.      Rectangle {}
  4.      Timer {}
  5.  }

instead of:

  1.  Item {
  2.      children: [ //default property and implicitly assigned
  3.          Text {},
  4.          Rectangle {}
  5.      ]
  6.      resources: [ //default property and implicitly assigned
  7.          Timer {}
  8.      ]
  9.  }

The anchors.horizontalCenter: parent.horizontalCenter statement aligns the center of the text with the center of the parent rectangle. Anchors provide a way to position an item by specifying its relationship with parent or sibling items. (Note – if you check the online documentation for the Rectangle element you will not see the anchors.horizontalCenter property listed. Look closely and you will see the Rectangle element inherits all the properties of the Qt Quick Item element; the Item element provides the anchors.horizontalCenter property.)

There are currently seventeen anchor properties available, allowing you to align, center, and fill elements relative to each other and to set margins and offsets. For example, Snippet 4 shows a Text element anchored to an Image element, horizontally centered and vertically below, with a margin.

  1. Image { id: pic; ... }
  2.  Text {
  3.      id: label
  4.      anchors.horizontalCenter: pic.horizontalCenter
  5.      anchors.top: pic.bottom
  6.      anchors.topMargin: 5
  7.      ...
  8.  }

Snippet 4: Use anchors to align elements

Layering visual elements

Visual elements can be layered on top of each other with transparency using opacity : real where real varies from 0 (transparent) to 1 (opaque). For performance reasons this should be used sparingly, especially in animations as each layer in the scene will need to be rendered at runtime for each frame of the animation. This may be fine for rapid prototyping, but before final deployment it is best to pre-render as much of the scene as possible, then simply load pixel maps at runtime.

Snippet 5 produces two offset and overlapping rectangles, one red and one blue, with transparency invoked such that the overlapping square will be purple. Notice how the child (blue) rectangle inherits the 50% opacity from its parent (red) rectangle.

  1.      Rectangle {
  2.          id: parentRectangle
  3.          opacity: 0.5
  4.          color: "red"
  5.          width: 100; height: 100
  6.          Rectangle {
  7.              id: childRectangle
  8.              color: "blue"
  9.              x: 50; y: 50; width: 100; height: 100
  10.          }
  11.      }

Snippet 5: Use transparency sparingly

Tech Note: Inherited Elements always inherit their base Element properties. For example a Rectangle is an Item, so all properties of an Item will always be present in a Rectangle Element. Child objects can sometimes inherit the properties of their parents due to how QGraphicsView works. This means that when you embed an element within another element certain properties have an effect on its children. For example in Snippet 5 the childRectangle element is affected by the 50% opacity of the parentRectangle element. Similarly, if the parentRectangle was rotated, the childRectangle would keep its rotation relative to parentRectangle but would be rotated relative to the scene.

Interaction elements: mouse and touch

To add mouse or touch interaction you need to add a MouseArea object. The MouseArea object lets the user click and drag the mouse (or touch point). Other available interaction elements include Flickable, Flipable, and FocusScope.

Note that the MouseArea object can be separate from any visually apparent objects, providing the designer flexibility. It is quite possible, for example, to create a visual representation of button for a user to click and then surround the visual representation with a larger mouse area that allows the user to “miss” the visible element by a few pixels.

To introduce a mouse region to the Hello World example, the rectangle containing the text is made a child of a new rectangle that will define the mouse area.

  1. import Qt 4.7
  2.  
  3. Rectangle {
  4.     color: "#ff0000"
  5.     width: 310
  6.     height: 210
  7.     MouseArea {
  8.             anchors.fill: parent
  9.             onClicked: {
  10.                 if(parent.color == "#ff0000") {
  11.                     parent.color = "#ff9900";
  12.                 } else {
  13.                     parent.color = "#ff0000";
  14.                 }
  15.             }
  16.     }
  17.     Rectangle {
  18.               width: 300
  19.         height: 200
  20.         anchors.horizontalCenter: parent.horizontalCenter
  21.         anchors.verticalCenter: parent.verticalCenter
  22.  
  23.         Text {
  24.             anchors.horizontalCenter: parent.horizontalCenter
  25.             anchors.verticalCenter: parent.verticalCenter
  26.             text: "Hello World"
  27.         }
  28.     }
  29. }

Snippet 6: Mouse-touch interaction

The MouseArea element includes signal handlers that allow you to write JavaScript expressions that will be called upon certain events or changes in state. Available handlers include onClicked, onEntered, onExited, onPressed and onReleased. In the example above, the onClicked signal handler toggles the color of the rectangle.

This example changes the color of the rectangle in response to any valid click. A click is defined as a press followed by a release, both inside the MouseArea (pressing, moving outside the MouseArea, and then moving back inside and releasing is also considered a click). The full syntax for the handler is MouseArea::onClicked ( mouse ) where the mouse parameter provides information about the click, including the x and y position of the release of the click, and whether the click was held. Our example does not care where the click occurred.

Snippet 6 shows a simple case of visualizing state by changing one value in response to one event. The onClicked statement will quickly become ugly if you try to change multiple values in response to multiple states. That’s where Qt Quick state declarations come in.

State declarations

Qt Quick State declarations define a set of property value changes from the base state. The base state is the initial declaration of property values, and is expressed by using an empty string as the state name. After a state change you can always revert to the base state by assigning state=”“ .

In Snippet 7, states for two colors are implemented. In the definition of the red rectangle, the id property is set. Named objects can be referenced by siblings or descendants. Two states are also defined: red and orange. The state property is assigned to give the element an initial state.

State elements include a when condition that can be used to determine when a state should be applied. Here you see the red state applied when the Mouse Area is currently being pressed.

  1.         id: buttonRect;
  2.  
  3.         state: "red"
  4.         states: [
  5.             State {
  6.                 name: "red"
  7.                 when: mouseArea.pressed == true
  8.                 PropertyChanges {
  9.                     target: buttonRect;
  10.                     color: "red";
  11.                     width: 80; height: 40
  12.                 }
  13.             },
  14.             State {
  15.                 name: "orange"
  16.                 when: mouseArea.pressed == false
  17.                 PropertyChanges {
  18.                     target: buttonRect;
  19.                     color: "#ff9900";
  20.                     width: 120; height: 80
  21.                 }
  22.             }
  23.         ]

Snippet 7: Define states

The defined state not only sets the color for each state, but also the width and height of the rectangle. The orange state provides a larger button. To utilize the states, the mouse region onClicked JavaScript is updated.

  1.         MouseArea {
  2.             anchors.fill: parent
  3.             onClicked: {
  4.                 if(parent.state == "red") {
  5.                     parent.state = "orange"
  6.                 } else {
  7.                     parent.state = "red";
  8.                 }
  9.             }
  10.         }

Snippet 8: Simple state transitions

It is possible to define a set of states using code, as in this example, or using the graphical Qt Quick Designer built into the Qt Creator IDE.

Animation elements: fluid transitions

Transition elements make it easy to create fluid animation effects between states of a UI. Transition elements can use the information from the base state and the target state to interpolate property changes using Animation elements. Animation elements in turn can use a number of different parametized easing curves and grouping techniques, giving the developer and designer a high degree of control over how and when properties change during a state transition.

Transitions between states are only one animation possibility in Qt Quick. Suppose a Rectangle’s movement – that is, changes in its x or y property values – should be animated. The semantics of the animation differ depending on whether you want to create:

  • An animation that moves the Rectangle as soon as it is created, to a known position
  • An animation that only triggers when the Rectangle is moved by external sources – for example, when the mouse is clicked, animate the movement to the mouse position
  • An animation that triggers when a particular signal is received
  • A standalone animation that is not bound to the Rectangle’s movement, but instead can be started and stopped from script as required
  • An animation that only triggers during state changes

There is a detailed treatment of these possibilities in the animation in Qt Quick article in the online documentation. As an introduction, let’s consider the case where transitions provide animations between state changes.

The code in Snippet 9 animates the movement of a rectangle. The snippet creates a Rectangle object with two states: the default state, and an added moved state. In the moved state, the rectangle’s position changes to (50, 50). The Transition object specifies that when the rectangle changes between the default and the moved state, any changes to the x and y properties should be animated, using an Easing.InOutQuad.

  1. import QtQuick 1.1
  2.  
  3.  Rectangle {
  4.      id: rect
  5.      width: 100; height: 100
  6.      color: "red"
  7.  
  8.      states: State {
  9.          name: "moved"
  10.          PropertyChanges { target: rect; x: 50; y: 50 }
  11.      }
  12.  
  13.      transitions: Transition {
  14.          PropertyAnimation {
  15.              properties: "x,y";
  16.              easing.type: Easing.InOutQuad
  17.          }
  18.      }
  19.  }

Snippet 9: Animated state transitions

You can apply multiple transitions to an item as in Snippet 10: Multiple transitions. (Remember anything you can do to an item you can do to a Rectangle). By default a transition is applied to all state changes. For greater control you can set the from and to properties to apply a transition only when changing from a given state, to a given state, or between given states.

  1. Item {
  2.      ...
  3.      transitions: [
  4.          Transition { ... }
  5.          Transition { ... }
  6.      ]
  7.  }

Snippet 10: Multiple transitions

Building reusable components

The discussion of Snippet 1: Hello World described the contents of a QML document. How a QML document is named matters. A QML document name that begins with an uppercase case letter defines a single, reusable, top-level component. A component is a template that is interpreted by the QML runtime to create an object with some predefined behavior. As it is a template, a single component can be “run” multiple times to produce several objects, each of which are said to be instances of the component.

Once created, instances are not dependent on the component that created them, so they can operate on independent data. Here is an example of a simple Button component (defined in a Button.qml file) that is instantiated four times by application.qml. Each instance is created with a different value for its text property:

  1. import QtQuick 1.1
  2.  
  3.  Rectangle {
  4.      property alias text: textItem.text
  5.  
  6.      width: 100; height: 30
  7.      border.width: 1
  8.      radius: 5
  9.      smooth: true
  10.  
  11.      gradient: Gradient {
  12.          GradientStop { position: 0.0; color: "darkGray" }
  13.          GradientStop { position: 0.5; color: "black" }
  14.          GradientStop { position: 1.0; color: "darkGray" }
  15.      }
  16.  
  17.      Text {
  18.          id: textItem
  19.          anchors.centerIn: parent
  20.          font.pointSize: 20
  21.          color: "white"
  22.      }
  23.  
  24.  }

Snippet 11: The Button.qml file creates a button component

  1. import QtQuick 1.1
  2.  
  3.  Column {
  4.      spacing: 10
  5.  
  6.      Button { text: "Apple" }
  7.      Button { text: "Orange" }
  8.      Button { text: "Pear" }
  9.      Button { text: "Grape" }
  10. }

Snippet 12: Use the button four times with different text properties.

Note that QML documents may also create components inline using the Component element.

Using pre-built Qt Components

You don’t necessarily have to build components yourself; there are several sources of pre-built components you can use.

Qt Components from Nokia is a library developed using the same open processes of the rest of the Qt framework. You can find the latest builds on gitorious, and the latest stable releases in the SDK and official documentation. Qt Quick Components are built on top of Qt Quick and provide native-look user interface elements for your application. They are bundled together as a module that you can import into your QML file. Once you have imported the components module, you can use the components just as you would use standard Qt elements such as Rectangle and Text. You may then implement the business logic of your application with JavaScript or Qt C++.

The components are implemented separately for both Symbian and MeeGo to match the native look and feel of each platform. Components from both sets have similar interfaces and many components share a common interface. The compatible interfaces allow the developers to share some common code but give the freedom to customize their applications to each platform.

There are also many open source projects that offer Qt Quick Components for free use. The Qt Quick Open Components article offers a comprehensive list of available libraries.

Snippet 13 illustrates the Button from the Qt Components library. When the user presses the button, it sends a clicked signal.
You can set a button to be a toggle button by enabling the checkable property.

On Symbian platforms, the button can also respond to a long-press. The button sends platformPressAndHold signal once when the user presses the button for a long period of time. If the button’s platformAutoRepeat property is true, the button sends the clicked signal repeatedly as long as the user presses the button.

The snippet and screen shot illustrates the case where the user has set the ‘Signals’ button’s platformAutoRepeat property to true. When the user presses the ‘Signals’ button it sends a clicked signal repeatedly as long as the user keeps the button pressed. When the user releases the button it sends in Symbian environment a platformReleased signal.

  1.          Button {
  2.              id: btnSignals
  3.              anchors.left: parent.left
  4.              anchors.right: parent.right
  5.              text: "Signals"
  6.  
  7.              // bind platformAutoRepeat to the "checked" checkbox
  8.              platformAutoRepeat: chkPlatformAutoRepeat.checked
  9.  
  10.              // bind checkable to the "checkable" checkbox  
  11.              checkable: chkCheckable.checked    
  12.              onPlatformReleased: {
  13.                  txtLog.text =
  14.                     txtLog.text
  15.                     + "The 'platformReleased' signal. <br>"
  16.              }
  17.              onClicked: {
  18.                  txtLog.text =
  19.                     txtLog.text
  20.                     + "The 'clicked' signal. <br>"
  21.              }
  22.              onPlatformPressAndHold: {
  23.                  txtLog.text =
  24.                     txtLog.text
  25.                     + "The 'platformPressAndHold' signal. <br>"
  26.              }
  27.          }

Snippet 13: Using the Button from Qt Component library.

Model-View pattern

Using QML in a model-view design pattern is a natural. QML can create fluid, visually appealing views into models whether the models are created in C++ or directly in QML.

Qt Quick currently provides three elements devoted to creating views into models. The ListView and GridView elements create list and grid views respectively. The PathView element lays out model-provided items on a path, for example a loop path that allows you to create a carousel interface into a list.

Let’s create two different views into the same model – a basic contact list.

You can build models directly in QML using the ListModel element among others. Snippet 14 shows how to create a contacts model where each contact record includes a name, a phone number, and an icon. Each element in the list is defined by a ListElement element; each entry includes two data roles, name and icon. Save the document in the file ContactModel.qml for access later. (Notice the initial cap that makes this file an accessible component.)

  1. import QtQuick 1.1
  2.  
  3.  ListModel {
  4.      ListElement {
  5.          name: "Bill Jones"
  6.          number: "+1 800 555 1212"
  7.          icon: "pics/qtlogo.png"
  8.      }
  9.      ListElement {
  10.          name: "Jane Doe"
  11.          number: "+1 800 555 3434"
  12.          icon: "pics/qtlogo.png"
  13.      }
  14.      ListElement {
  15.          name: "John Smith"
  16.          number: "+1 800 555 5656"
  17.          icon: "pics/qtlogo.png"
  18.      }
  19.  }

Snippet 14: Defining a List Model in QML

Snippet 15 uses the ListView element to lay out items horizontally or vertically. The snippet sets the model property to the ContactModel component just created. The delegate property provides a template defining each item instantiated by the view. In this case, the template shows the name and number roles using the built-in Text component. If you choose, you can define delegate components the same way you define any other component.

Tech note: when using C++ models, the names used to refer to the different roles of the model are set using the QAbstractItemModel::setRoleNames method. More on C++ models later in the Using Qt Quick in C++ applications section.

  1. import QtQuick 1.1
  2.  
  3.  ListView {
  4.      width: 180; height: 200
  5.  
  6.      model: ContactModel {}
  7.      delegate: Text {
  8.          text: name + ": " + number
  9.      }
  10.  }

Snippet 15: List view into contact model

Now let’s get a little fancier and build a view into the contacts model that looks like a 3D carousel and allows the user to flick her way through the list. The resulting view and code is shown in Snippet 16. Note the creation of an inline component for use as the delegate property in the PathView element.

  1. import QtQuick 1.1
  2.  
  3.  Rectangle {
  4.      width: 240; height: 200
  5.  
  6.      Component {
  7.          id: delegate
  8.          Column {
  9.              Image { anchors.horizontalCenter:
  10.                     name.horizontalCenter;
  11.                     width: 64; height: 64;
  12.                     source: icon
  13.              }
  14.              Text { text: name; font.pointSize: 16 }
  15.          }
  16.      }
  17.  
  18.      PathView {
  19.          anchors.fill: parent
  20.          model: ContactModel {}
  21.          delegate: delegate
  22.          path: Path {
  23.             startX: 120; startY: 100
  24.             PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
  25.             PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
  26.          }
  27.      }
  28.  }

Snippet 16: Rotating carousel view into contact model

Qt Creator

Qt Creator is a development environment built for collaboration between designers and developers. Designers work in a visual environment, developers work in a full-featured IDE, and Qt Creator supports round-trip iteration from design, to code, to test, and back to design.

A full treatment of Qt Creator is available online. Here we will just introduce key ways the tool allows designers and developers to interact.
Qt Creator for Designers

Qt Creator for Designers

For designers, Qt Creator includes a visual editor for QML files called Qt Quick Designer. It allows you to rapidly design and build Qt Quick applications and components from scratch. It is completely integrated into Qt Creator and works seamlessly with the QML code editor.

With Qt Quick Designer you can:

  • Design Qt Quick user interfaces with drag and drop functionality
  • Customize components or choose from library of standard QML elements
  • Preview QML files instantly without compilation
  • Use Qt Quick components for MeeGo and Symbian

Figure 1: Drag and drop QML elements into a scene

Exporting Designs from Adobe Photoshop and other Graphics Software

The art embedded in QML projects can be imported from popular graphics software including Adobe Photoshop and GIMP. Each scene is converted into a single QML file with an Image or a Text element for each layer and saved on the development PC. Top-level layer groups are converted into merged QML Image elements.

You can open the QML file in Qt Creator for editing. If you edit the file in Adobe Photoshop and export it to the same directory again, any changes you made in Qt Creator are overwritten. However, you can re-export graphical assets without recreating the QML code.

Figure 2: Export Photoshop projects to QML shows how to use a custom plug-in to export your Photoshop projects. See the documentation for full instructions and a link to the current plug-in.

Figure 2: Export Photoshop projects to QML

Qt Creator for Developers

Qt Creator makes it easy to switch from a visual editor when working with designers and a code editor when fine tuning design or building application logic.

In Projects, double-click a .qml file to open it in the code editor. Snippet 17 shows the QML code used to place rectangle between two adjacent elements.

  1. Rectangle {
  2.      id: rectangle2
  3.      anchors.right: rectangle3.left
  4.      anchors.rightMargin: 15
  5.      anchors.left: rectangle1.right
  6.      anchors.leftMargin: 15
  7.      anchors.bottom: parent.bottom
  8.      anchors.bottomMargin: 15
  9.      }

Snippet 17: Code-level view of anchor specification for a QML element

From here you can click Design mode to edit the file in the visual editor. Figure 3: Visual view of anchor specification shows the same specification; changes made in one view are immediately updated in the other.

Figure 3: Visual view of anchor specification

Implementing over-sized MouseArea

Much earlier in this paper we mentioned QML provides the flexibility to make an active MouseArea larger than the visual representation of it to increase usability of a design. Here is how you would implement this technique in Qt Creator.

When you initially drag a MouseArea element on top of an image, the bounds of the child MouseArea will be within the parent. After placing the element, go into its properties window and exapand it. Figure 4 shows a typical result.

Figure 4: Implementing an over-sized MouseArea

Integration with C++ applications

Qt Quick comes with its own runtime and enables loading new functionality via modules, making it possible to develop applications built entirely with QML. However, the real strength of Qt Quick is the ability to integrate it into a C++ application.

For the most basic needs, for example integrating a QML view into a C++ project, the QDeclarativeView widget can be used. It is derived from a QGraphicsView but also includes the required components to host a QML view. Alternatively, you can simply make new C++ types available to the QML runtime through plugins, and these types can do anything your C++ application can do.

For more complex situations, how you proceed depends on from how the C++ code is built.

If you are starting with an application based on C++ widgets, you can reuse all your graphics assets and re-factor the QWidgets to QML. Since you already have the full interaction and design work done, developing and coding the QML is relatively easy.

If you are instead starting with an application based on a QGraphicsView, the conversion process is even easier and can proceed in stages. The entire QML-based application can be inserted into an existing graphics view by instantiating a QML engine. If desired, the QML interface can co-exist with the existing user interface and allow the conversion process to proceed in steps.

Snippet 17 shows the three steps required to add a QML engine and context to an existing QGraphicsView. First create an environment for instantiating QML components using the QDeclarativeEngine class, then encapsulate a QML component definition using QDeclarativeComponent. Finally, the resulting QGraphicsObject can be added to the existing scene and co-exist with the rest of the user interface.

  1. QGraphicsScene *scene = ...;
  2.  
  3. QDeclarativeEngine *engine = new QDeclarativeEngine;
  4. QDeclarativeComponent component(engine, QUrl::fromLocalFile(...));
  5. QGraphicsObject *object =
  6.     qobject_cast<QGraphicsObject*>(component.create());
  7.  
  8. scene->addItem(object);

Snippet 18: Adding a QML engine to QGraphicsView

If the component fails to load the QML file, the error property will be set to true. To output the error messages, the following statement can be placed just after the call to create.

qWarning() << component.errors();

Tech note: the syntax above is only available if you include <QtDebug> in your project. See documentation about qWarning() for details.
To align the user interfaces it is possible to transform the QGraphicsObject and adjust the z-value to place it at the right depth in the scene. In order to achieve the optimal performance for the QML part of the user interface, the following options are recommended to be set.

  1. QGraphicsView *view =;
  2.  
  3. view->setOptimizationFlags(QGraphicsView::DontSavePainterState);
  4. view->setViewportUpdateMode(
  5.     QGraphicsView::BoundingRectViewportUpdate);
  6. view->setItemIndexMethod(QGraphicsScene::NoIndex);

Snippet 19: Optimizing QML interface performance.

Although combining an existing graphics view-based user interface with QML is possible, it is recommended to convert the entire experience to Qt Quick.

Sharing data between C++ and QML

Qt Quick provides numerous ways to share data between C++ and QML with or without implementing a formal model-view design pattern. It is also possible to trigger calls to QML functions from C++ and vice-versa. In general, exposing a QObject will make all of its signals, slots and properties available to the QML environment.

All QML code executes within a context. The context keeps track of what data is available to different leaves and nodes in a QML object tree. Data is shared as context properties or context objects. A context property is simply a way to expose a given QObject through a given name. For example, to expose a QColor property named frameColor to QML, simply use the following snippet.

QDeclarativeContext *context = …;
context->setContextProperty(“frameColor”, QColor(Qt::red));
This property can then be accessed from within the QML context as a global property, as shown below. Remember property values are bound, not assigned, in QML. This means you can alter the frameColor property from C++ and the change will be reflected in QML.

  1. Rectangle {
  2.     border.color: frameColor
  3. }

It is possible to add multiple context properties to a QDeclarativeContext object, but as the list of properties climbs the readability of the code crumbles. Instead of setting each property individually, it is cleaner to gather all context properties into one QObject and set the single object as the context object instead.

Snippet 19 shows how to define the interface object MyInterface using the setContextProperty method. The Q_PROPERTY macro defines the properties available within MyInterface to the Qt property system and sets notification signals, allowing subsequent bindings to work.
Note that all properties added explicitly by QDeclarativeContext::setContextProperty() take precedence over the context object’s default properties.

  1. class MyInterface : ... {
  2.      ...
  3.      Q_PROPERTY(QAbstractItemModel *myModel READ model NOTIFY modelChanged)
  4.      ...
  5.  };
  6.  
  7.  MyInterface *myInterface = new MyInterface;
  8.  QDeclarativeEngine engine;
  9.  QDeclarativeContext *context = new
  10.     QDeclarativeContext(engine.rootContext());
  11.  context->setContextObject(myDataSet);
  12.  QDeclarativeComponent component(&engine);
  13.  component.setData("import Qt 4.7\nListView {
  14.    model: myModel }", QUrl());
  15.  component.create(context);

Snippet 20: Defining an interface using setContextProperty

QML views into C++ models

Object properties work well when providing a limited set of values to QML, but are difficult to manage when large data sets are involved. In these cases formal models are visualized with formal views. This model/view design pattern allows developers to separate the implementation of user interface from business logic, supporting the model-view design pattern. The model can be implemented in C++ while the view is coded in QML.

QML can create views into C++ models that are exposed using the QAbstractItemModel interface.

To expose a QAbstractItemModel to QML a context property is used:

  1. QAbstractItemModel *model =;
  2. context->setContextProperty("dataModel", model);

Tech Note: Within Qt, the QAbstractItemModel class provides the abstract interface for item model classes. The QAbstractItemModel class defines the standard interface that item models must use to be able to interoperate with other components in the model/view architecture. It is not supposed to be instantiated directly. Instead, you should subclass it to create new models.

The QAbstractItemModel class is one of the Model/View Classes and is part of Qt’s model/view framework.

QML / C++ program flow

Qt Quick allows QML to call C++ methods and allows C++ signals to be handled by JavaScript expressions within the QML context.

Calling C++ methods from QML

In order to feedback data from the user to the business logic, QML must be able to call C++ methods. This is achieved through slots or Q_INVOKABLE methods. By providing QML access to a QObject as a context property, the slots and invokable methods of that class can be called from QML.

For example, the following QObject derived class is added to the QML context.

  1. class CallableClass : public QObject
  2. {
  3.     Q_OBJECT
  4.     ...
  5. public slots:
  6.     void cppMethod() { qDebug("C++ method called!"); }
  7. };
  8.  
  9. ...
  10.  
  11. context->setContextProperty("cppObject", new CallableClass);

The QML code then can refer to the cppMethod method using the cppObject global object. In this example the method in question returns no value nor accepts any arguments, but that is not a limitation of QML. Both return values and arguments of the types supported by QML are supported.

  1. MouseArea {
  2.     ...
  3.     onClicked: {
  4.         cppObject.cppMethod();
  5.     }
  6. }

Qt signal -> QML handler

Qt C++ signals can be handled by JavaScript executing in a QML context. For instance, the CallableClass class from the previous example also declares a signal, cppSignal.

  1. class CallableClass : public QObject
  2. {
  3.     Q_OBJECT
  4.     ...
  5. signals:
  6.     void cppSignal();
  7. };

Using a Connections Qt Quick element, a signal handler can be implemented in QML. The connections element can be used to handle signals for any target object, including other Qt Quick elements. The signal handler is called onSignalName, where the first letter of the signal name is capitalized.

  1. Connections {
  2.     target: cppObject
  3.     onCppSignal: { console.log("QML function called!"); }
  4. }

Extending QML from C++

Qt Quick has built-in support for an extensive set of element types, but when application-specific needs pop up it is possible to extend QML with custom element types built in C++. For example, let’s say you have a burning desire for a Qt Quick element called Person with properties name and shoeSize.

All Qt Quick elements map to C++ types. Snippet 20 declares a basic C++ class Person with the two properties we want accessible on the QML type – name and shoeSize. Although in this example we use the same name for the C++ class as the Qt Quick element, the C++ class can be named differently, or appear in a namespace.

  1.  class Person : public QObject
  2.  {
  3.      Q_OBJECT
  4.      Q_PROPERTY(QString name READ name WRITE setName)
  5.      Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
  6.  public:
  7.      Person(QObject *parent = 0);
  8.  
  9.      QString name() const;
  10.      void setName(const QString &);
  11.  
  12.      int shoeSize() const;
  13.      void setShoeSize(int);
  14.  
  15.  private:
  16.      QString m_name;
  17.      int m_shoeSize;
  18.  };

Snippet 21: Declare a Person class

  1. Person::Person(QObject *parent)
  2.  : QObject(parent), m_shoeSize(0)
  3.  {
  4.  }
  5.  
  6.  QString Person::name() const
  7.  {
  8.      return m_name;
  9.  }
  10.  
  11.  void Person::setName(const QString &n)
  12.  {
  13.      m_name = n;
  14.  }
  15.  
  16.  int Person::shoeSize() const
  17.  {
  18.      return m_shoeSize;
  19.  }
  20.  
  21.  void Person::setShoeSize(int s)
  22.  {
  23.      m_shoeSize = s;
  24.  }

Snippet 22: Define the Person class

The Person class implementation is quite basic. The property accessors simply return members of the object instance.

The main.cpp file also calls the qmlRegisterType() function to register the Person type with QML as a type in the People library version 1.0, and defines the mapping between the C++ and Qt Quick class names.

The Person type can now be used from QML:

  1.  import People 1.0
  2.  
  3.  Person {
  4.      name: "Bob Jones"
  5.      shoeSize: 12
  6.  }


h1. Getting started

This paper provided a brief introduction to Qt Quick. There is plenty more information, tutorials, and code examples for you to explore.

For additional information about Qt Quick:

  • Try the QML Tutorial at http://doc.trolltech.com/4.7/qml-tutorial.html
  • Full documentation of Qt Quick elements is online at http://doc.trolltech.com/4.7/qdeclarativeelements.html
    To begin working with Qt Quick:
  • Download and install the latest Qt Creator IDE 2.3, which now includes a QML Text Editor with code completion, syntax highlighting and context-sensitive help; a Qt Quick designer that was built from the ground up using QML; and a QML Debugger that allows you to inspect the QML item tree and its properties at runtime, to check frame rates, to evaluate JavaScript expressions and so on inside QtCreator.
  • Once you install Qt Creator, check out the included examples installed in the YourInstalledRoot/examples/declarative directory and exposed through the IDE.
  • You will find an online discussions and wikis covering Qt Quick at www.forum.nokia.com/Community and at http://developer.qt.nokia.com/

Categories: