Qt Quick Carousel Tutorial

From Qt Wiki
Revision as of 16:52, 14 January 2015 by Maintenance script (talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

English Български

The Qt Quick Carousel Tutorial


This tutorial will show you how to create an animated menu with items rotating in a pseudo 3D space. You will also be shown how to break up a QML project into several modules as well as how to add support for different languages using Qt Linguist.

All you need is the qmlviewer tool in order to follow this tutorial. If you are running a recent version of Linux, simply install the qt4-qmlviewer and libqt4-dev packages. All files in this tutorial are available from gitorious [gitorious.org] .

The minimum required Qt Quick version is 1.0, which has been shipping with Qt since version 4.7.1.

Getting to know the PathView

The PathView [developer.qt.nokia.com] element takes items out of a model and lays them out along a path. The path geometry is defined by a series of segments. There are three different types of segments: lines, quadratic and cubic Bézier [en.wikipedia.org] curves. To develop an understanding of how to construct a path, let us start with a single line segment:

The PathView is our top-level element. Providing just an item count 32 as model automatically generates model indexes ranging from 0 to 31. For each item a delegate is instantiated to display that item. We start with simple text elements to display the index numbers. We will see later how to create more meaningful delegates — for now let us focus on how to create paths. The path specification requires at least a starting point and a single segment. In our case we start at (0, 0) and draw a single line segment to the bottom right. Loading this file with the qmlviewer gives you an output similar to:

When you drag the items, the path view will kinematically scroll. Notice how it locks back into a fixed position. By default, the first item is centered at the starting point, while the rest of the items are distributed evenly along the path.

OK, let’s add some complexity and draw a full rectangle. Replace the path specification from the previous example and add the following:

You will see a rectangle. Each PathLine [developer.qt.nokia.com] starts at the end point of the previous segment, so we only need to specify the end point for each line segment. For the last segment, we just reference the starting point to close the loop. We’ve introduced the custom property pathMargin to help define the path’s geometry. Using custom properties is the easiest way to introduce helper variables in Qt Quick, but use this feature wisely because all properties in Qt Quick are public.

You might have wanted to write:

…but this is not possible as the Path component is already defined elsewhere and we are not allowed to add new properties on the fly.

The quadrature of the circle

Now that we’ve learned how to create a rectangle, let’s try something a bit more difficult: a circle. The Path element itself does not support circular curves and therefore we have to approximate using one of the less favorable choices: lines, quadratic or cubic Bézier splines. As this is not a discussion about analytical geometry, let’s jump to the best result in an instant: 4 cubic Bézier splines using the magic number 0.551784 [tinaja.com]. Take a look at the code:

Which gives us a picture-perfect circle:

As you can see, we need two control points for each cubic Bézier path segment. (All points are given in absolute coordinates.) If we had gone with quadratic Bézier curves, we only would have needed one single control point per segment. The control points lie outside the curvature, but influence its shape. You should be familiar with the concept from popular vector graphics tools.

Hiding complexity

A QML file can be defined to be a re-usable component [doc.qt.nokia.com]. When you grow your code, you commonly want to split out generic elements into separate files to enable reuse and increase readability. In our example we would want to write:

Our self-defined Ellipse component hides all the complexity of the circle approximation and scaling. When we define our own components derived from exiting ones, we can also introduce new properties. The Ellipse component contains the following code, which is a slightly generalized version of our earlier circle approximation:

As you can see, we’ve decided to start in the second quadrant. The idea is to have the first item on the path shown in the bottom-most position, which is also the position of the current item.

Adding the artwork

At this point, you should have developed a basic understanding of how to manage paths. This leaves us with doing the real magic: bringing the artwork to life. We have chosen a small tron-style [dirtydogicons.com] icon set and we will directly go ahead and make it appear in 3D. It is astonishingly simple in QML to do so.

First, let’s create the necessary model. We’ve started with a simple dummy model and will now replace it with a real model. Here’s the code:

We’ve chosen to use a ListModel [developer.qt.nokia.com] and we populate it with our custom list elements. We are free to define our own properties for the items. We’ll use the iconSource to display the menu icon and the title to add a title display later-on. Our new delegate is based on the Image component and looks like the following:

Not much code, right? But it already has everything needed for a gorgeous 3D menu. We trick the eye into believing it is 3D by scaling the icons down towards the top. Reducing opacity in the distance also helps the depth perception. If you open Carousel4.qml in qmlviewer it gives you:


Adding keyboard interaction

Adding keyboard interaction is quite simple and straight forward. First we have to add the following three lines of code to process the keyboard events:

All the visual elements have a focus property. Only one element at a time should have it set to true and this element is the one that receives keyboard input events. We use the attached Keys [developer.qt.nokia.com] properties to implement the event handlers. We could also have used the more elaborate keyboard event handler:

As you can see, we are counting the current index up or down when a key is pressed. But which one is actually the current item? As the path view can take up any abstract shape, how can it know which one should be the currently active item if any? The current item is also called the highlighted item and you have to add the following lines to tell the PathView which item to highlight:

In our case, we decided to make the first item on the path the current item. Now, as we have defined the current item, we should be able to navigate the menu by either incrementing or decrementing the current index. Try it out by opening Carousel5.qml in the qmlviewer.

Fine tuning

Finally we’d like to display the title of the current item. The PathView has a highlightItem which we could use to create a highlight, but we will simply bind a Text [developer.qt.nokia.com] item to the geometry of the root element to display the title. This also shows how you can link up components from different places.

Qt Quick provides a rich set of attributes for text styling. The color value paleturquoise is one of the SVG color names [w3.org].
As you can see, we’ve bound the text directly to the title stored in our model. This type of binding is quick and easy. Whenever the currentIndex changes, QML will automatically reevaluate the text. But beware the risks here. Do not over-use direct bindings across different object hierarchies. For instance when we decide to rename the model attribute title to something else, we are breaking all property bindings which include the title and we won’t get a warning until the component is actually instantiated.


There are many topics we could have talked about in this small tutorial, which was meant to be provide a quick tour through Qt Quick, but talking about things like C++ bindings, packaging or deployment would certainly have made us depart far from our initial goal of keeping things simple. There is, however, one important point we can still include here and that is internationalization. Usually a quite complex topic, Qt makes translating applications astonishingly simple.

Qt includes Qt Linguist [developer.qt.nokia.com], which is a powerful tool for translating applications. The same procedures used for C++ code also apply for QML with the exception of a few differences [developer.qt.nokia.com]

Strings that should be translated into QML need to be wrapped with the qsTr() function. The lupdate tool is then able to extract those strings and generate XML translation files (.ts extension). The interpreter can then add translations using Qt Linguist and, once they have been added, the resulting .ts files are compiled into .qm files using lrelease. To test a translation simply pass the .qm file to the qmlviewer with the -translation command line option.

There are a few tricky parts along the road you have to know about, so let’s walk through the process with our small carousel menu and translate the title texts shown below the current item. You might think you could just wrap the title text in the model like this:

But that’s not going to work, because script expressions are not allowed for the property values of a list element. There are few obvious choices on how to work around that issue. As JavaScript functions are allowed practically everywhere we have chosen to rewrite the title property as a function:

As you can see we call qsTr() for each menu item the first time the title() function is called. Of course you have to use such constructs only, if you are dealing with translating model values. All other strings can be wrapped directly with qsTr().
As we have changed the model definition, we also need to refactor the dependent code. In our case we are lucky and only need to replace one line:

Now we call lupdate to generate the XML translation files:

Then open this file with the linguist and enter your translations. Once you’ve finished, invoke lrelease:

The lrelease tool will generate a new Carousel_de.qml translation file. You can test the translation by invoking the qmlviewer from the command line like the following:


The icons used in this article were created by dirtydogicons.com [dirtydogicons.com] .