Introduction to Qt Quick for C++ Developers/el

From Qt Wiki
Jump to navigation Jump to search
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

Ελληνικά English "French":http://qt-devnet.developpez.com/tutoriels/qt-quick/pour-developpeurs-cpp/

[toc align_right="yes" depth="2"]

http://qt.nokia.com/logo.png

Εισαγωγή στο Qt Quick για C++ Developers

Σήμερα, οι καταναλωτές και οι εμπορικοί χρήστες είναι δύσκολο να ικανοποιηθούν. Μεγαλώνουν χρησιμοποιώντας slick UI στις παιχνιδομηχανές τους και βλέπουν ακόμη πιο εντυπωσιακά UI στις ταινίες. Τα specification και οι feature lists από μόνα τους δεν είναι πλέον σημεία πωλήσεων, αλλά είναι τα μέσα για ένα σκοπό. Visual impact και experience WOW είναι τα σημεία πωλήσεων που έχουν σημασία σήμερα, και ο καταναλωτής περιμένει αυτό το visual delight κάθε φορά που χρησιμοποιεί ένα ισχυρό εταιρικό υπολογιστή notebook, ένα set-top box, ή μία φορητή συσκευή.

Η επίτευξη αυτής της εμπειρίας απαιτεί σχεδιαστές και developers να δουλεύουν μαζί όπως ποτέ στο παρελθόν. Στο παρελθόν ανήκουν οι μέρες όπου οι σχεδιαστές μπορούσαν να παραθέτουν pixel maps στον τοίχο και να περιμένουν τους developers να υλοποιήσουν το όραμα τους. Στο παρελθόν ανήκουν επίσης οι μέρες που οι developers μπορούσαν να προγραμματίζουν μόνο με σκοπό τις επιδόσεις χωρίς να λαμβάνουν υπόψη το ελκυστικό οπτικά αποτέλεσμα. Σχεδίαση/development/test πρέπει να γίνουν έναν επαναληπτικός κύκλος, όχι ένα γραμμικό μονοπάτι.

Το Qt Quick είναι φτιαγμένο για τον τρόπο που οι ομάδες παραγωγής εργάζονται σήμερα. Η Core business logic προγραμματίζεται από τους developers και βελτιστοποιείται σε σχέση με την απόδοση, το interface χτίζεται από σχεδιαστές που εργάζονται με visual tools, και η χρήση ολοκληρωμένων εργαλείων υποστηρίζει αλληλοδιάδοχες επαναλήψεις μεταξύ των περιοχών.

Το Qt Quick έχει ως αποτέλεσμα επιδόσεις διότι κάθεται πάνω στο Qt framework για εφαρμογές και UI. Το Qt framework είναι γνωστό για την υψηλή runtime απόδοση και το μικρό footprint, γεγονός που το κάνει ιδανικό για mobile, embedded, και netbook εφαρμογές.

Το Qt Quick επεκτείνει το Qt framework με την QML, μια δηλωτική γλώσσα που κωδικοποιεί τον τρόπο που σκέφτονται οι σχεδιαστές. Κάθε frame ενός story board δηλώνεται ως ένα branch σε ένα element tree. Κάθε οπτική πτυχή ενός frame δηλώνεται ως μια ιδιότητα στοιχείων στο branch. Κάθε μετάβαση μεταξύ frames μπορεί να διακοσμηθεί με μια πλειάδα από animations και effects.

Το Qt Quick περιλαμβάνει τον Qt Creator, ένα περιβάλλον development φτιαγμένο για τη συνεργασία μεταξύ σχεδιαστών και developers. Οι σχεδιαστές εργάζονται σε ένα οπτικό περιβάλλον, οι developers εργάζονται σε ένα IDE πλήρες προσόντων, και ο Qt Creator υποστηρίζει αλληλοδιάδοχες επαναλήψεις για τη σχεδίαση, τη συγγραφή κώδικα, το test, και ξανά πίσω στη σχεδίαση.

Επισκόπηση του Qt Quick

Το Qt Quick αποτελείται από τη γλώσσα QML, το "QtDeclarative":http://doc.qt.nokia.com/4.7/qtdeclarative.html C++ module το οποίο ολοκληρώνει τη γλώσσα QML με C++ αντικείμενα, και το εργαλείο Qt Creator το οποίο πλέον περιλαμβάνει επεκτάσεις για την υποστήριξη του περιβάλλοντος. Το Qt Quick βοηθά τους προγραμματιστές και τους σχεδιαστές να συνεργάζονται στη δημιουργία των fluid user interfaces που γίνονται κοινός τόπος στις φορητές καταναλωτικές συσκευές, όπως τα κινητά τηλέφωνα, τα media players, τα set-top boxes και τα netbooks. Χρησιμοποιώντας το "QtDeclarative":http://doc.qt.nokia.com/4.7/qtdeclarative.html C++ module, μπορείτε να φορτώσετε QML αρχεία και να αλληλεπιδράσετε με αυτά μέσα από την Qt εφαρμογή σας.

Η QML παρέχει μηχανισμούς για το δηλωτικό χτίσιμο ενός δέντρου αντικειμένων "QML elements":http://doc.qt.nokia.com/4.7/qdeclarativeelements.html. Η QML βελτιώνει την ολοκλήρωση μεταξύ της JavaScript και των υπαρχόντων "QObject":http://doc.qt.nokia.com/4.7/qobject.html της Qt, προσθέτει υποστήριξη για αυτόματα "property bindings":http://doc.qt.nokia.com/4.7/propertybinding.html και παρέχει "network transparency":http://doc.qt.nokia.com/4.7/qdeclarativenetwork.html σε επίπεδο γλώσσας.

Τα "QML elements":http://doc.qt.nokia.com/4.7/qdeclarativeelements.html είναι ένα σοφιστικέ σετ από γραφικά και συμπεριφορικά δομικά στοιχεία. Αυτά τα διαφορετικά στοιχεία συνδυάζονται μαζί στο "QML documents":http://doc.qt.nokia.com/4.7/qdeclarativedocuments.html για τη δημιουργία συστατικών με πολυπλοκότητα που ποικίλει από απλά κουμπιά και sliders, μέχρι ολόκληρες internet-enabled εφαρμογές σαν έναν "Flickr":http://www.flickr.com photo browser.

Το Qt Quick πατάει πάνω στα "δυνατά στοιχεία του Qt":http://doc.qt.nokia.com/4.7/qtprogrammers.html. Η QML μπορεί να χρησιμοποιηθεί για την κλιμακωτή επέκταση μιας υπάρχουσας εφαρμογής ή για τη δημιουργία εντελώς νέων εφαρμογών. Η QML είναι πλήρως "επεκτάσιμη από τη C+":http://doc.qt.nokia.com/4.7/qml-extending.html μέσω του "QtDeclarative":http://doc.qt.nokia.com/4.7/qtdeclarative.html module.

http://doc.qt.nokia.com/whitepapers/qml-for-cpp-whitepaper/creator-design.png

Το user interface του Qt Creator για τη δημιουργία συστατικών του Qt Quick

h1. Μια σύντομη εισαγωγή στην QML

Η QML είναι μια πλούσια γλώσσα, και μια πλήρης περιγραφή είναι πέρα από τους σκοπούς αυτού του άρθρου. Αυτό το άρθρο εναλλακτικά θα παρουσιάσει μία εισαγωγή στο τι μπορεί να κάνει η QML και στο πώς μπορείτε να ολοκληρώσετε την QML με C+ για να πάρετε το καλύτερο και από τους δύο κόσμους: υψηλών επιδόσεων business logic built σε C++ και πολύ δυναμικές διεπαφές χρήστη με χρήση της QML. Μια πλήρης περιγραφή της QML είναι διαθέσιμη στο "online documentation":http://doc.qt.nokia.com/4.7/declarativeui.html.

Η κατανόηση της QML αρχίζει με τη έννοια των "elements":http://doc.qt.nokia.com/4.7/qdeclarativeelements.html. Ένα element είναι ένα template για μία βασική δομική μονάδα από την οποία μπορεί να φτιαχτεί ένα πρόγραμμα σε QML. Η QML υποστηρίζει για παράδειγμα οπτικά elements των τύπων Rectangle και Text, αλληλεπιδραστικά elements των τύπων

MouseArea

και

Flipable

, και animation elements των τύπων

RotationAnimation

και

Transition

. Υπάρχουν επίσης πολύπλοκοι τύποι element που επιτρέπουν στον developer να εργαστεί με δεδομένα, να υλοποιήσει views σε αρχιτεκτονικές model-view, καθώς και άλλοι τύποι housekeeping element οι οποίοι απλά θα προσθέσουν σύγχυση στην παρούσα φάση. Όλα τα QML elements περιλαμβάνουν μία ή περισσότερες ιδιότητες (για παράδειγμα

color

) οι οποίες μπορεί να ελεγχθούν από τον developer και πολλά elements περιλαμβάνουν σήματα (signals) (για παράδειγμα

onClicked

) τα οποία μπορεί να χρησιμοποιηθούν για την απόκριση σε events ή σε αλλαγές κατάστασης.

Οπτικά elements: Hello World

Αρκετά με το κείμενο! Είναι ώρα για το απαραίτητο Hello World παράδειγμα. Ακολουθεί ο απαιτούμενος κώδικας για την τοποθέτηση του κειμένου Hello World στην επιφάνεια ενός background rectangle:

import Qt 4.7

Rectangle {
 width: 300
 height: 200
 Text {
 anchors.horizontalCenter: parent.horizontalCenter
 anchors.verticalCenter: parent.verticalCenter
 text: "Hello World"
 }
}

Απόσπασμα κώδικα: Hello World

Ας μελετήσουμε αυτό το απλό πρόγραμμα. Το παράδειγμα Hello World είναι ένα έγγραφο QML, πράγμα που σημαίνει ότι είναι ένα πλήρες block QML πηγαίου κώδικα, έτοιμου για εκτέλεση. Τα έγγραφα QML γενικά αντιστοιχούν σε plain αρχεία κειμένου αποθηκευμένα σε ένα δίσκο ή πόρο δικτύου, αλλά μπορούν να δημιουργηθούν άμεσα από δεδομένα κειμένου.

Ένα έγγραφο QML πάντα αρχίζει με μία ή περισσότερες εντολές import. Εδώ βλέπετε το import του Qt 4.7. Για να εμποδιστούν στοιχεία που θα παρουσιαστούν σε επόμενες εκδόσεις να επηρεάσουν υπάρχοντα έγγραφα QML, οι διαθέσιμοι τύποι στοιχείων μέσα σε ένα έγγραφο ελέγχονται από τα imported "QML Modules":http://doc.qt.nokia.com/4.7/qdeclarativemodules.html. Αυτό σημαίνει ότι η QML είναι μία versioned γλώσσα.

Το επόμενο που βλέπετε είναι το Rectangle element template που χρησιμοποιείται για τη δημιουργία ενός ενεργού αντικειμένου. Τα αντικείμενα μπορεί να περιέχουν άλλα αντικείμενα, να δημιουργούν σχέσεις parent-child. Στο παραπάνω πρόγραμμα, το αντικείμενο Rectangle είναι parent στο αντικείμενο Text. Το στοιχείο Rectangle επίσης ορίζει ένα top-level παράθυρο για τη διαχείριση των οπτικών ορίων και του focus segmentation ολόκληρου του UI.

Μέσα στα αντικείμενα, οι ιδιότητες δένονται με τιμές χρησιμοποιώντας την property : expression statement. Υπάρχουν δύο πτυχές αυτής της statement που χρήζουν επεξήγησης.

Πρώτον, η expression είναι μία JavaScript expression, το οποίο σημαίνει ότι μπορείτε να ορίσετε τις ιδιότητες με βάση έναν υπολογισμό, μια συνθήκη, ή άλλες πολύπλοκες εντολές JavaScript. Για παράδειγμα, μπορείτε να ορίσετε το aspect ratio ενός rectangle με βάση την τιμή μιας variable orientation.

Δεύτερον, το binding είναι διαφορετικό από την ανάθεση (assignment). Στην ανάθεση, η τιμή μιας ιδιότητας ορίζεται όταν η εντολή ανάθεσης εκτελείται και είναι σταθερή στη συνέχεια μέχρι και εάν η εντολή εκτελεστεί ξανά. Σε ένα binding, μια ιδιότητα ορίζεται όταν η εντολή binding εκτελείται για πρώτη φορά, αλλά θα τροποποιηθεί εάν και όταν το αποτέλεσμα της έκφρασης που χρησιμοποιείται για τον ορισμό της ιδιότητας αλλάξει. (Εάν είναι επιθυμητό, μπορείτε να αναθέσετε μια τιμή στην ιδιότητα χρησιμοποιώντας ιδιότητα = έκφραση μέσα σε ένα JavaScript block.)

Σκεφθείτε τι συμβαίνει όταν ο προσανατολισμός της συσκευής αλλάζει από portrait σε landscape (πιθανόν λόγω ενός αισθητήρα σε μια φορητή συσκευή). Λόγω των property bindings, το aspect ratio του parent rectangle θα αλλάξει και τα text element anchors will θα ανταποκριθούν στην αλλαγή για να θέσουν ξανά το κείμενο στο κέντρο.

Η δήλωση

anchors.horizontalCenter: parent.horizontalCenter

στοιχίζει το κέντρο του κειμένου με το κέντρο του parent rectangle. Τα Anchors παρέχουν τη δυνατότητα τοποθέτησης ενός στοιχείου καθορίζοντας τη σχέση του με το parent ή με τα sibling στοιχεία. (Σημείωση: 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 QML

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, The following snippet shows a

Text

element anchored to an

Image

element, horizontally centered and vertically below, with a margin.

http://doc.qt.nokia.com/whitepapers/qml-for-cpp-whitepaper/anchors.png

Text {
 id: label
 anchors.horizontalCenter: pic.horizontalCenter
 anchors.top: pic.bottom
 anchors.topMargin: 5
 
}

Snippet: Use anchors to align elements


Layering visual elements

QML 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.

The following snippet 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.

http://doc.qt.nokia.com/whitepapers/qml-for-cpp-whitepaper/transparency.png

Rectangle {
 opacity: 0.5
 color: "red"
 width: 100; height: 100
 Rectangle {
 color: "blue"
 x: 50; y: 50; width: 100; height: 100
 }
}

Snippet: Use transparency sparingly


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.

import Qt 4.7

Rectangle {
 color: "#ff0000"
 width: 310
 height: 210
 MouseArea {
 anchors.fill: parent
 onClicked: {
 if (parent.color == "#ff0000") {
 parent.color = "#ff9900";
 } else {
 parent.color = "#ff0000";
 }
 }
 }
 Rectangle {
 width: 300
 height: 200
 anchors.horizontalCenter: parent.horizontalCenter
 anchors.verticalCenter: parent.verticalCenter

Text {
 anchors.horizontalCenter: parent.horizontalCenter
 anchors.verticalCenter: parent.verticalCenter
 text: "Hello World"
 }
 }
}

Snippet: 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":http://doc.qt.nokia.com/4.7/qml-mousearea.html (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. The Mouse-touch interaction snippet 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 QML state declarations come in.

State Declarations

QML 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 an empty string to the

state

property.

In the following snippet, states for the 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

MouseArea

is currently being pressed.

id: buttonRect;

state: "red"
states:
 State {
 name: "red"
 when: mouseArea.pressed  true
        PropertyChanges {
            target: buttonRect;
            color: "red";
            width: 80; height: 40
        }
    },
    State {
        name: "orange"
        when: mouseArea.pressed  false
 PropertyChanges {
 target: buttonRect;
 color: "#ff9900";
 width: 120; height: 80
 }
 }

Snippet: 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.

MouseArea {
 anchors.fill: parent
 onClicked: {
 if (parent.state == "red") {
 parent.state = "orange"
 } else {
 parent.state = "red";
 }
 }
}

Snippet: 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 component in Qt Creator.

To create animations between states, transition elements are defined. Transition elements can use the information from the base state and the target state to interpolate the property changes using Animation elements. Animation elements in turn can use a number of different parametrized 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. This is discussed in further detail later on.

QML components

The discussion of the Hello World snippet described the contents of a QML document. How a QML document is named also matters. A QML document name that begins with an uppercase case letter defines a single, top-level "QML component":http://doc.qt.nokia.com/4.7/qdeclarativecomponent.html. A QML component is a template that is interpreted by the QML runtime to create an object with some predefined behaviour. As it is a template, a single QML 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:

http://doc.qt.nokia.com/whitepapers/qml-for-cpp-whitepaper/buttons.png

import Qt 4.7

Column {
 spacing: 10

Button { text: "Apple" }
 Button { text: "Orange" }
 Button { text: "Pear" }
 Button { text: "Grape" }

Snippet: Use the button four times with different text properties


import Qt 4.7

Rectangle {
 property alias text: textItem.text

width: 100; height: 30
 border.width: 1
 radius: 5
 smooth: true

gradient: Gradient {
 GradientStop { position: 0.0; color: "darkGray" }
 GradientStop { position: 0.5; color: "black" }
 GradientStop { position: 1.0; color: "darkGray" }
 }

Text {
 id: textItem
 anchors.centerIn: parent
 font.pointSize: 20
 color: "white"
 }

}

Snippet: The Button.qml file creates a button component


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

Animation elements: fluid transitions

Animation effects are key to a fluid UI. In QML, animations are created by applying animation objects to object property values to gradually change them over time. Animation objects are created from the built-in set of animation elements, which can be used to animate various types of property values. In addition, animation objects can be applied in different ways depending on the context in which they are required.

There is a detailed treatment of "animation in QML":http://doc.qt.nokia.com/4.7/qdeclarativeanimation.html in the online documentation. As an introduction, let's consider transitions.

The following snippet shows the code to animate 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

.

import Qt 4.7

Rectangle {
 id: rect
 width: 100; height: 100
 color: "red"

states: State {
 name: "moved"
 PropertyChanges { target: rect; x: 50; y: 50 }
 }

transitions: Transition {
 PropertyAnimation {
 properties: "x,y";
 easing.type: Easing.InOutQuad
 }
 }
}

Snippet: Animated state transitions


You can apply multiple transitions to an item as in the following snippet. (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.

Item {
 
 transitions:
 Transition {  }
 Transition {  }

}

Snippet: Multiple transitions


Model-View pattern in QML

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.

QML 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. The following snippet 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 capital letter that makes this file an accessible component.)

import Qt 4.7

ListModel {
 ListElement {
 name: "Bill Jones"
 number: "+1 800 555 1212"
 icon: "pics/qtlogo.png"
 }
 ListElement {
 name: "Jane Doe"
 number: "+1 800 555 3434"
 icon: "pics/qtlogo.png"
 }
 ListElement {
 name: "John Smith"
 number: "''1 800 555 5656"
 icon: "pics/qtlogo.png"
 }
}

Snippet: Defining a List Model in QML

p.

The following snippet 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 QML component.

import Qt 4.7

ListView {
 width: 180; height: 200

 model: ContactModel {}
 delegate: Text {
 text: name'' ": " + number
 }
}

Snippet: 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 the following snippet . Note the creation of an inline component for use as the delegate property in the

PathView

element.

import Qt 4.7

Rectangle {
 width: 240; height: 200

Component {
 id: delegate
 Column {
 Image { anchors.horizontalCenter:
 name.horizontalCenter;
 width: 64; height: 64;
 source: icon
 }
 Text { text: name; font.pointSize: 16 }
 }
 }

PathView {
 anchors.fill: parent
 model: ContactModel {}
 delegate: delegate
 path: Path {
 startX: 120; startY: 100
 PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
 PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
 }
 }
}

Snippet: Rotating carousel view into contact model

p.

h1. Using Qt Quick in C++ applications

Qt Quick comes with its own run-time 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 application. 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":http://doc.qt.nokia.com/4.7/qgraphicsview.html, the conversion process is even easier and can proceed in stages. The entire QML 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.

The following snippet 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":http://doc.qt.nokia.com/4.7/qdeclarativeengine.html class, then encapsulate a QML component definition using "QDeclarativeComponent":http://doc.qt.nokia.com/4.7/qdeclarativecomponent.html. Finally, the resulting "QGraphicsObject":http://doc.qt.nokia.com/4.7/qgraphicsobject.html can be added to the existing scene and co-exist with the rest of the user interface.

QGraphicsScene *scene = ;

QDeclarativeEngine *engine = new QDeclarativeEngine;
QDeclarativeComponent component(engine, QUrl::fromLocalFile());
QGraphicsObject '''object =
 qobject_cast<QGraphicsObject'''>(component.create());

scene->addItem(object);

Snippet: 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();

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.

QGraphicsView *view = ;

view->setOptimizationFlags(QGraphicsView::DontSavePainterState);
view->setViewportUpdateMode(
 QGraphicsView::BoundingRectViewportUpdate);
view->setItemIndexMethod(QGraphicsScene::NoIndex);

Snippet: 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.

Rectangle {
 border.color: frameColor
}

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.

The following snippet 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()":http://doc.qt.nokia.com/4.7/qdeclarativecontext.html#setContextProperty take precedence over the context object's default properties.

class MyInterface :  {
 
 Q_PROPERTY(QAbstractItemModel *myModel READ model NOTIFY modelChanged)
 
};

MyInterface *myInterface = new MyInterface;
QDeclarativeEngine engine;
QDeclarativeContext *context = new
 QDeclarativeContext(engine.rootContext());
context->setContextObject(myInterface);
QDeclarativeComponent component(&amp;engine;);
component.setData("import Qt 4.7\nListView { model: myModel }", QUrl());
component.create(context);

Snippet: 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":http://doc.qt.nokia.com/4.7/qabstractitemmodel.html interface.

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

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

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.

class CallableClass : public QObject
{
 Q_OBJECT
 
public slots:
 void cppMethod() { qDebug("C++ method called!"); }
};



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.

MouseArea {
 
 onClicked: {
 cppObject.cppMethod();
 }
}

Qt signal to 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()

.

class CallableClass : public QObject
{
 Q_OBJECT
 
signals:
 void cppSignal();
};

Using a

Connections

QML element, a signal handler can be implemented in QML. The connections element can be used to handle signals for any target object, including other QML elements. The signal handler is called

onSignalName

, where the first letter of the signal name is capitalized.

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

Extending QML from C++

QML 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 QML element called

Person

with properties

name

and

shoeSize

. All QML elements map to C+ types. The following snippet 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 QML element, the C++ class can be named differently, or appear in a namespace.

class Person : public QObject
{
 Q_OBJECT
 Q_PROPERTY(QString name READ name WRITE setName)
 Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)

public:
 Person(QObject *parent = 0);

QString name() const;
 void setName(const QString &amp;);

int shoeSize() const;
 void setShoeSize(int);

private:
 QString m_name;
 int m_shoeSize;
};

Declare a Person class

Person::Person(QObject '''parent)
: QObject(parent), m_shoeSize(0)
{
}

QString Person::name() const
{
 return m_name;
}

void Person::setName(const QString &amp;n)
{
 m_name = n;
}

int Person::shoeSize() const
{
 return m_shoeSize;
}

void Person::setShoeSize(int s)
{
 m_shoeSize = s;
}

Snippet: Define the Person class

p.

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()":http://doc.qt.nokia.com/4.7/qdeclarativeengine.html#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 QML class names.

#include <QtDeclarative>
…………
qmlRegisterType<Person>("People", 1, 0, "Person");

The

Person

type can now be used from QML:

import People 1.0

Person {
 name: "Bob Jones"
 shoeSize: 12
}

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.qt.nokia.com/4.7/qml-tutorial.html":http://doc.qt.nokia.com/4.7/qml-tutorial.html

  • Full documentation of QML elements is online at
"http://doc.qt.nokia.com/4.7/qdeclarativeelements.html":http://doc.qt.nokia.com/4.7/qdeclarativeelements.html

To begin working with Qt Quick:

  • Download latest "Qt SDK":http://qt.nokia.com/downloads/ which has tools ( including Qt libraries, Qt Creator IDE ) you need to build desktop, embedded and mobile applications with Qt from a single install. This is the recommended way to get started with Qt. The latest SDK has a self updater feature that will keep you up to date as new versions are made available.
  • Or download and install snapshots of the latest Qt Creator IDE 2.1, which previews a QML Text Editor with code completion, syntax highlighting and context-sensitive help; a QML Visual Editor 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 Qt Creator. Qt Creator 2.1 is scheduled for release later in 2010.
  • 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
"http://www.developer.nokia.com/Community":http://www.developer.nokia.com/Community
and at
"http://developer.qt.nokia.com/":http://developer.qt.nokia.com/

http://doc.qt.nokia.com/whitepapers/qt-creator-whitepaper/wiki-images/share.png http://doc.qt.nokia.com/whitepapers/qt-creator-whitepaper/wiki-images/remix.png http://doc.qt.nokia.com/whitepapers/qt-creator-whitepaper/wiki-images/by.png http://doc.qt.nokia.com/whitepapers/qt-creator-whitepaper/wiki-images/sa.png

This document is licensed under the "Creative Commons Attribution-Share Alike 2.5":http://creativecommons.org/licenses/by-sa/2.5/ license.

For more information, see "http://creativecommons.org/licenses/by-sa/2.5/legalcode":http://creativecommons.org/licenses/by-sa/2.5/legalcode for the full terms of the license.

http://doc.qt.nokia.com/whitepapers/qt-creator-whitepaper/wiki-images/nokia-logo.png