Qt Declarative UI

Published Wednesday May 13th, 2009
39 Comments on Qt Declarative UI
Posted in Qt, Qt Quick, Qt Script

We’ve hinted a bit about the Declarative UI part of Kinetic. Well, now it’s time to take a look.

First, here is a video of QML in action:

and some more here:

To run the examples for real, either download a binary package including Qt Creator integration, or grab the full source code from the public Gitorious repository.

Declarative UI is a way of making fluid user interfaces by describing them in terms of simple elements (Text, Image, Rect,and other QObjects) that are built up into components. The reason it is “declarative” is that rather than the changes in the UI being expressed as imperative code (“set this, set that, do this, do that, …”), they are instead expressed as sets of QObject property expressions (“this width is always half that width”), grouped into states (“when enabled, the properties are …, when disabled, they are …”).  The language that enables this is named QML.  QML is simple yet powerful. Most of a user interface is described by a simple tree structure of property bindings:

import Qt 4.6

Rectangle {
    width: 200
    height: 200
    color: "white"
    Text {
        text: "Hello World"
        anchors.centerIn: parent
    }
}

The power is that those property values can be any JavaScript expression – and because it’s a binding rather than just an assignment, the expressions are re-evaluated whenever their dependencies change. This concept has been in Qt forever – if you go back to the old cannon tutorial where a QLCDNumber’s display was connected to a QSlider’s value, that’s a binding: the number displayed changes automatically when the slider value changes.

The fluid part comes from animated transitions between the sets of properties. Combined with Qt’s signals and slots, and a little bit of script for the tricky parts, the result is a very powerful technology for making very cool looking UIs that are enjoyable to use.  There is also a set of building blocks useful for creating a fluid UI, including drawing (e.g. Rect, Image), behavior (e.g. MouseRegion, Flickable) and layout (e.g. ListView).  These sorts of fluid user interfaces work well for small simple user interfaces such as those on a phone, or gadget-style desktop applications like media players or VoIP clients. We’ve put a couple of demos like this in qt/demos/declarative/ directory of the source.

For larger applications, especially on the desktop, fancy effects are currently mainly at the fringes – the bulk of any large application will use traditional widgets (there’s a lot of value in desktop consistency!), with just a little “fluidness” at the edges to give the apps a modern feel.

On the web side of things, Declarative UI is completely network transparent – if so configured, Qt will happily load a complete declarative user interface incrementally via HTTP – images and all. And since Declarative UI can use Qt’s XQuery support to process other remote data, there are quite a few applications you can write completely in script – no C++ at all.

Qt Declarative integrates perfectly with existing Qt C++ applications.  Qt Declarative components can expose an API with signals, slots, and properties.  For example, the QML below defines a simple button with an API consisting of a label property and the signal clicked():

import Qt 4.6

Rectangle {
    id: container
    property string label
    signal clicked
    radius: 5; border.color: "black"
    color: mouse.pressed ? "steelblue" : "lightsteelblue"
    gradient: Gradient {
            GradientStop { position: mouse.pressed ? 1.0 : 0.0; color: "steelblue" }
            GradientStop { position: mouse.pressed ? 0.0 : 1.0; color: "lightsteelblue" }
    }
    MouseRegion { id: mouse; anchors.fill: parent; onClicked: container.clicked() }
    Text { anchors.fill: parent; text: container.label; anchors.centerIn: parent }
}

We can create this component in C++ and access its API, just like any other Qt QObject subclass:

QmlComponent component(qmlEngine, "Button.qml");

QObject *button = component.create();

button->setProperty("label", tr("Press Me!"));

connect(button, SIGNAL(clicked()), this, SIGNAL(buttonClicked()));

Qt’s data models also work immediately with QML.  Just expose the C++ model to the QML engine:

MyFancyModel *model = new MyFancyModel();

QmlContext *ctxt = canvas->rootContext();

ctxt->setContextProperty("MyModel", model);

Then reference the model’s name in QML:

Rectangle {
    width: 800; height: 600; color: "black"

    ListView {
        anchors.fill: parent
        model: MyModel
        delegate: Text { text: display; color: "white" }
    }
}

Declarative UI is a new way to use the core concepts of Qt, so it fits in with your existing code.

We’ve already started integrating Declarative UI support in Qt Creator. Right now you get QML syntax highlighting and an integrated viewer – check out the Qt Creator blog for details.

And in the KDE playground, there is a demonstration of KDE Plasma integration, so you can run any Declarative UI as a Plasmoid on the desktop!

Do you like this? Share it
Share on LinkedInGoogle+Share on FacebookTweet about this on Twitter

Posted in Qt, Qt Quick, Qt Script

39 comments

Anon says:

Very impressive stuff, but I have to ask – who sacrificed a finger to make that video? 😉

Thorbjørn Lindeijer says:

Binary packages of Qt Creator with integrated Qt Declarative UI support can be found on ftp://ftp.trolltech.com/declarativeui/. Note that you will still need a build of Qt Kinetic to preview the QML files! (Windows users can use the qmlviewer.exe in the binary linked to from the blog)

Robert Knight says:

Nice. Something quite frustrating about desktop development compared with web stuff has been the lack of freedom in composing interfaces. In the web you can put pretty much anything inside anything else. Even Qt 4 up to now is quite limited in this respect, especially with item views. The ability to easily construct themed, animated and interactive elements in tables, lists, trees etc. would be really welcome.

notmart says:

can i say i love you?
no, really, this stuff is beyond rocking

timdewhirst says:

very impressive… however how does one go about debugging? How can you find out e.g. which rule is causing a particular behaviour?

QtDeclarative says:

You can see the beginnings of a debugger by setting the environment variable QML_DEBUGGER=1. This is still very experimental, but it will give you a sample of what is possible.

Scorp1us says:

Why CSS style and not XML, like .ui files?

I’d like something I can manipulate at runtime, like a DOM

Ricard says:

Wow! looks very promising. I’m going to go check out the code for the Flickr image viewer, it looks so sleek.
If only the image would zoom from the middle… it would be perfect, jejeje.

And the finger!!! LOL

Martin Tilsted says:

Nice but can the declarative system also be used to make a normal qt gui with widgets?
That is: Can it layout and set state for all QTWidgets?

Tim says:

Very iPhone-ish! Is this headed for a Nokia phone any time soon?

David Johnson says:

What’s the overhead cost for this on embedded devices?

Vincent Torri says:

That kind of scripting description of a UI is done in the Enlightenment Fundation Libraries (through the edje library, maybe you have heard of Qedje…) since years.

Jack Vance says:

Video reminds me of effects from compiz.

Vincent, I checked out Qedje, it is quite interesting too:

http://www.youtube.com/watch%3Fv%3DQZUwUDeJfX0&ei=_AULSs_qJ5eVkAXAmamyCw&usg=AFQjCNG8cM0M0RXhkDZj9Bx06zHlgXsCdA&sig2=01VdSg-0hBVHSjY9ULhN9g

ddevienne says:

JavaFX anyone 😉

shamaz says:

yes, it seems to share many concepts with javaFX. But… since thoses concepts are reaally good, I can accept that 😉
Does this new feature aim mobile devices like javaFX ?

Vitalyx says:

Impressive!! But how do I install and read docs from the “docsrcdeclarative” folder?

warwick says:

Re: Language syntax:

we tried a couple of syntaxes. The biggest trouble with XML is that everything is a string, whereas logically in QML, everything is a JS expression. This makes it rather ugly, as you either have to always dual-quote:

or otherwise mark javascript:

one obvious problem with the latter arises with i18n:

so rest assured, we carefully examined the syntax issue.

warwick says:

Re: JavaFX

Yes, JavaFX is cool. There are some significant differences that would require a boring discussion of QML bindings, but the BIG difference for people familiar with Qt is that building on top of the huge power of Qt gives QML a huge jump. As a quick example, you’ve used QAction in your apps, right? Well, they’re QObjects, so you can bind them straight into QML:

MyQmlButton {
text: MyApp.openAction.text
onClick:MyApp.openAction.activate()
}

Declarative UI encourages you to build powerful QObject abstractions in C++; you can then use them from more traditional QWidgets in C++, as objects in QML, or as the “meat” of a new QFxItem subclass. For example, QFxWebView and QWebView are both rather thin wrappers around QWebPage which is a QObject.

So what sets Declarative UI apart from JavaFX, Flash, and other similar technologies is what Qt brings underneath it all.

warwick says:

QWidget:

In theory (and in our prototypes), “Declarative” can also build and animate QWidget trees – it can build ANY system of QObjects. But you’ll have to excuse us for staying focused on one application of Declarative UI in the short term. What you do with the sources though is totally up to you (well, and up to the LGPL 😉

Hoang Vu says:

I have tried WPF and Silverlight. Will Declarative UI have the same amount of support from IDE and tools ? (This new Declarative UI really rocks).

warwick says:

Performance (embedded devices):

This is definitely the most pervasive part of the effort. You’ll already have seen the massive improvements in QGraphicsView. There is tightening up in lots of other places needed by Declarative UI too, all of which benefit all Qt programmers.

The specifics of Declarative UI are also tuned for performance. For example, the QML is compiled to an optimized bytecode-like stream; and the JavaScript expressions pass through an optimized evaluator for simple expressions.

We take performance very seriously: an animated UI at only 10 fps is just annoying.

Plenty of work still needs to be done though. Any hardware-specific test results (or patches!) gladly received!

warwick says:

Documentation in source package:

Normal Qt procedure: run “make docs”, then point web browser at doc/html/index.html

Then click on “Declarative Module” for the declarative UI docs, where you’ll find examples, tutorials, overviews, and reference for C++ classes and their corresponding QML elements.

mjones says:

@Ricard: Right you are. When gitorious next syncs you will find that the image zooms about the center of the visible area.

vohi says:

@Vitalyx: to generate documentation, make sure you have qdoc built in tools/qdoc3, then while in tools/qdoc3 run “qdoc3 test/qt.qdocconf”. The documentation main index will then end up as doc/html/index.html

Will add this to gitorious later today.

Suurenmoinen says:

It looks totally awesome but Im getting a crash with the listview demo.When I open the recipes.qml and scroll down when the view reaches the bottom of the last item (lemonade), the whole app crashes.

Henrik Hartz says:

@Hoang Vu on tool support; Yes we are aiming to enable the creation of Declarative UI’s in tools as well. Since this project is still very much under development we are not yet ready to commit to plans in this respect outside what we are saying in our public roadmap; http://www.qtsoftware.com/developer/qt-roadmap#qt-creator-2-0

jhc says:

Congratulations! Qt is finally working its way to what NeXT did 20 years ago!

No seriously, it’s very slick and a BIG improvement on the current approach. Generating UI data from Designer, then generating code from that, then subclassing it, then infecting your subclassed view with controller code was always wrongheaded from both the OOP and architectural viewpoints. I’m glad to see that approach going away.

Vitalyx says:

@vohi Thanks! Had some warnings, but all in all it worked.

Marko says:

Impressive work guys!

As far as I understood, base class for visuals in Declarative UI is QFxItem. In graphics view framework, the visual base class is QGraphicsItem. I know the two approaches can be easily mixed in an application. Can you say something about the future of the two frameworks. For example, have you any plans to provide a QFxItem-based widget library (buttons, combo boxes, sliders, …)? In new projects, is the Declarative UI always the recommended approach?

Kensai says:

The ‘listview’ example is great and I can already see much use for it.

I was wondering if you could give us something like a cross-platform Ribbon widget. Its value in Windows applications has been appreciated by many and you can’t underestimate Microsoft’s commitment for its future use. Many platforms (even MacOS although it might look weird there at the beginning!) will find useful a Declarative UI toolbar with a Ribbon-like behaviour.

drac says:

The package ftp://ftp.trolltech.com/declarativeui/qml-examples.zip contains binaries build with Visual Studio 2005 (MSVCR80.dll), just an example:

$ dumpbin /imports qmlviewer.exe | findstr MSVC
MSVCR80.dll

The README.txt states (and vcredist_x86.exe is the runtime for Visual C++ 2008)

To run:
1. Install the Microsoft Visual C++ 2008 Redistrbutable Package named “vcredist_x86.exe” in the zip file
2. Double click the qmlviewer.exe application

Any plans on writing an XAML to QML converter? It would be very good for users who want to import
resources from a WPF application.

Thierry says:

@Kensai: The ribbon is another control we’ve worked on a very long time ago. It was a project completely disconnected from DeclarativeUI. The big problem we had with it was the licence model chosen by Microsoft (including patents). It is not something we agreed on so we dropped that project at the time.

Scorp1us says:

After this sank, in I have two comments:
1. Can we repurpose QtDesigner for making these qml files? Do we really need to go back to hand-editing text files? You wouldn’t expect me to write Designer’s XML by hand…
2. Can we bind this to ActiveQt/ Google Native Code Client and replace Flash/Silverlight? Being a Qt-app developer, I’d love to have an preview on the website! Right now the best we can do is movies.

Kensai says:

Thierry, thank you for your answer.

I hope you retake this Ribbon project cause it seems that it will be a major Windows 7 (there called “Scenic”) native toolbar control. Since Qt strives to feel native in every platform it runs, mimicking this Ribbon/Scenic functionality will be paramount! Not to mention the productivity (thus real!) advantages and modern feel it gives to the applications it is applied.

The reason I mentioned it here at the Declarative UI topic was not to bring you off-topic, but to stress a point. Microsoft’s new Ribbon is built on WPF. If we consider Declarative UI as Qt’s answer to the WPF, designing a “QtRibbon” based on your new in-house technology will be amazing! 🙂

Apart from this I agree with Scorp1us, we will need a QML editor sooner or later.

warwick says:

@Scorp1us: QML is intended to be both hand-written and tool-written, whereas Qt Designer UI files are purely tool-written (plus the odd manual search&replace).

With syntax highlighting (like now in the Creator), writing QML is significantly easier than writing the equivalent C++ code.

QML is not at all intended to replace C++ though as others have asked. Initially we’re focusing on simple fancy UIs – later we’ll see how applicable the technique is to more traditional desktop UIs.

romulus says:

pretty cool! .. but animations were not so smooth nor fast that i would like to see. but but.. i probably will check this more closely in future. what about this, is it possible to “create” multiple object instances? is the target audience graphics/ui designer that can’t code or c++ programmer.

color: Mouse.pressed ? “steelblue” : “lightsteelblue”

color: Mouse.pressed.twice? “what” : “then”

Matthias Ettrich says:

@romulus On what device/computer did you judge the performance to be “not so smooth nor fast that I would like to see”? You cannot judge the actual performance based on the youtube screen cast. Warwick: Maybe we need a real video showing a device screen, so people do believe that the real frame rates exceed those of the human eye by far?

To answer your questions: of course the animations are fast and smooth, you can create multiple objects, and designers do amazing and very complex things with flash or dynamic HTML. Programmers tend to believe that anything that has to do with programming is a magical skill that only they can manage. Talk to your next flasher or web designer and be surprised. You might also be surprised by the amount of excel coding that your nearest finance guy does 🙂

BaiJing says:

Hi, I have a question about the demos you described. I cloned the git repository, but could not find the example source code you mentioned. I wonder how can I get the source code of the QML examples? Could you please point out the position of the examples?

Thanks.
/Jing

Vitaly says:

If I were to implement something like this:
http://www.simile-widgets.org/timeline/examples/jfk/jfk.html
would the Declarative UI be the right way to go?

Commenting closed.

Get started today with Qt Download now