This is not going to be a tutorial on QML. There are plenty of those. (See [2])

However, this will discuss some of the problems I encountered while implementing a calculator application. The purpose of this application is /not/ to make a calculator. The purpose is to explore C++/QtQuick interactions as they would happen in a large project.

So, the goal is to implement this ugly little calculator:

We’ll implement as much of it as we can in QML, but we won’t actually make it functional. (E.g. button presses with do “something”… but not necessarily the “right” thing.) So, here’s a quick scaffolding:[1]

/*                                      -*- mode:javascript -*-
 * Calculator.00.qml - a scaffolding for a calculator UI.
 * This code was written by Gabriel M. Beddingfield <>
 * in 2011.  It is placed in the public domain.

import QtQuick 1.0

Rectangle {
    id: iRoot;
    color: "gray";
    width: 200; height: 310;
    anchors.margins: 5;
    property string text: "0";

    Rectangle {
	id: iDisplay;
	color: "white";;
	anchors.left: parent.left;
	anchors.right: parent.right;
	anchors.margins: parent.anchors.margins;
	height: 42;
	radius: height/10;

	Text {
	    id: iDisplayText;
	    text: iRoot.text;
	    color: "black";
	    font.pixelSize: 24;
	    anchors.verticalCenter: parent.verticalCenter;
	    anchors.right: parent.right;
	    anchors.margins: 10;


    Grid {
	columns: 3;
	property int bw: (width - 2 * anchors.margins)/3;
	property int bh: bw;
	spacing: parent.anchors.margins; iDisplay.bottom;
	anchors.left: iRoot.left;
	anchors.right: iRoot.right;
	anchors.bottom: iRoot.bottom;
	anchors.margins: parent.anchors.margins;

	/* Row 0 */
	Rectangle { id: i7; width:; height:; }
	Rectangle { id: i8; width:; height:; }
	Rectangle { id: i9; width:; height:; }

	/* Row 1 */
	Rectangle { id: i4; width:; height:; }
	Rectangle { id: i5; width:; height:; }
	Rectangle { id: i6; width:; height:; }

	/* Row 2 */
	Rectangle { id: i1; width:; height:; }
	Rectangle { id: i2; width:; height:; }
	Rectangle { id: i3; width:; height:; }

	/* Row 3 */
	Rectangle { id: iC; width:; height:; }
	Rectangle { id: i0; width:; height:; }
	Rectangle { id: iPlus; width:; height:; }

This is something that anyone should be able to do after going through one of the QtQuick tutorials.[2] So, if this part makes your head spin, then you should go visit a more basic tutorial first.

You may notice that I’m using Hungarian notation for all of the Item id’s. (E.g. “id: iRoot;”). The reason is that this id name can be used anywhere, any time to refer to this object. Even in another QML file. I find this really confusing, and the “i” helps clear things up pretty quick.[3]

Abstracting the Buttons

Every button on the calculator has several things in common:

  • They should all have an identical style.
  • They all represent one thing (like the number ‘5’)
  • When the user presses them, we want an event to notify us. Otherwise, we don’t really care how the button works.
  • We know that we need at least 12 of them.

If you’ve done Qt programming, you might think, “Easy… just use a QPushButton.” However, there is not such animal in QML. So right off the bat, we’re needing to make a custom widget. At first this may seem like a pain, but the truth is that in C++ we would also need a custom widget. We just wouldn’t write it until later because it’s extra work.

The design is pretty simple. We want the button to configure itself and send us a signal when it gets clicked. In other words here’s all we really care about:

Item {
    property string text: "X"

    signal postValue(string val);

    /* ...*/

Beyond that, we don’t really care what it does or how it works, right? The rest of it is really internal. So a no-frills button would look like this. Note: it’s very important that the file be named “Button.qml”. It’s not just the file-name, that’s how you name your custom element. Here’s the implementation:

/*                                      -*- mode:javascript -*-
 * Button.qml
 * This code was written by Gabriel M. Beddingfield <>
 * in 2011.  It is placed in the public domain.

import QtQuick 1.0

Item {
    /* This should be set by the parent element */
    property string text: "X"

    /* These should EXIST in the parent element, or be set
     * BY the parent element.  They are referred to by the
     * child elements.
    height: parent ? parent.button_height : 42;
    width: parent ? parent.button_width : 42;
    property color button_color_top: parent ? parent.button_color_top : "white";
    property color button_color_bot: parent ? parent.button_color_bot : "gray";
    property color text_color: parent ? parent.text_color : "black";

    /* These properties may be set by the parent element */
    property int font_pixel_size: 24;
    property int radius: (height < width) ? height/8 : width/8;

    /* This signal will fire when we get clicked, and contain the
     * text of the button.
    signal postValue(string val);

    /* Main geometry of button */
    Rectangle {
	id: iRectangle;
	anchors.fill: parent; /* parent is iRoot */
	radius: parent.radius;

	gradient: Gradient {
	    /* parent.button_color_* is implied */
	    GradientStop { position: 0.0; color: button_color_top; }
	    GradientStop { position: 1.0; color: button_color_bot; }

    /* Text display of button */
    Text {
	id: iText;
	text: parent.text; /* without 'parent.' this would be ambiguous */
	color: text_color; /* parent.text_color implied */
	font.pixelSize: font_pixel_size;
	anchors.centerIn: parent;

    /* This enables mouse interaction with button */
    MouseArea {
	id: iMouseArea;
	anchors.fill: parent;
	onClicked: {

This implementation shouldn’t be too much of a surprise. Here’s a few things to note:

  • The base thing is Item. The Rectangle is actually an implementation detail. By making the base an Item, we’re free to (for example) rotate the Rectangle 90° in order to get a left-to-right gradient. Now the Item is a meta-object the contains mostly meta-data (including the signal).
  • Every button needs an identical height, width, color, etc. Instead of copying the code over and over in Calculator.qml, I have the Button query the parent object for what these properties should be.
  • QML’s scoping rules allow us to access the parent’s properties and variables without qualifying them with “parent.”. However, in some cases this is ambiguous and we have to explicitly reference ‘parent.’ Whether you always use “parent” or not is a matter of style.
  • When the MouseArea “clicked” signal fires, we override its “onClicked” method to fire our own custom signal. We need to do this so that the button’s value can be sent in the signal.

Try out Button.qml using the qmlviewer test app:

    $ qmlviewer Button.qml

Putting the Buttons in the Calculator

Now we plug it in to our calculator. We also add a ‘color’ property to the grid to make it easier for the buttons to auto-configure themselves.[4] Here’s the changes we make:

--- Calculator.00.qml
+++ Calculator.01.qml
@@ -1,5 +1,5 @@
 /*                                      -*- mode:javascript -*-
- * Calculator.00.qml - a scaffolding for a calculator UI.
+ * Calculator.01.qml - Uses the Button element.
  * This code was written by Gabriel M. Beddingfield <>
  * in 2011.  It is placed in the public domain.
@@ -38,8 +38,11 @@

     Grid {
 	columns: 3;
-	property int bw: (width - 2 * anchors.margins)/3;
-	property int bh: bw;
+	property int button_width: (width - 2 * anchors.margins)/3;
+	property int button_height: button_width;
+	property color button_color_top: "#8888FF";
+	property color button_color_bot: "blue";
+	property color text_color: "black";
 	spacing: parent.anchors.margins; iDisplay.bottom;
 	anchors.left: iRoot.left;
@@ -48,23 +51,23 @@
 	anchors.margins: parent.anchors.margins;

 	/* Row 0 */
-	Rectangle { id: i7; width:; height:; }
-	Rectangle { id: i8; width:; height:; }
-	Rectangle { id: i9; width:; height:; }
+	Button { id: i7; text: "7"; }
+	Button { id: i8; text: "8"; }
+	Button { id: i9; text: "9"; }

 	/* Row 1 */
-	Rectangle { id: i4; width:; height:; }
-	Rectangle { id: i5; width:; height:; }
-	Rectangle { id: i6; width:; height:; }
+	Button { id: i4; text: "4"; }
+	Button { id: i5; text: "5"; }
+	Button { id: i6; text: "6"; }

 	/* Row 2 */
-	Rectangle { id: i1; width:; height:; }
-	Rectangle { id: i2; width:; height:; }
-	Rectangle { id: i3; width:; height:; }
+	Button { id: i1; text: "1"; }
+	Button { id: i2; text: "2"; }
+	Button { id: i3; text: "3"; }

 	/* Row 3 */
-	Rectangle { id: iC; width:; height:; }
-	Rectangle { id: i0; width:; height:; }
-	Rectangle { id: iPlus; width:; height:; }
+	Button { id: iC; text: "C"; }
+	Button { id: i0; text: "0"; }
+	Button { id: iPlus; text: "+"; }

The calculator doesn’t do anything yet, but it now looks the way that we want it. We simply replaced the Rectangle items with our custom Button elements.

I’ve not yet decided if using parent.button_height and friends is good design or not, but it at least saves a bunch of copy-and-paste.

Try out Calculator.01.qml using the qmlviewer test app:

      $ qmlviewer Calculator.01.qml

Note that you must also have Button.qml in the same folder.

Prototyping the interface

To get this data to our C++ app, we’ll need to set up the signals and slots that we’ll use to communicate with the core model of the application. What we need is:

  • A signal from the UI to the engine when a button is pressed, and which will carry the data that the button represents. We’ll call the signal ‘data
  • A signal from the engine to the UI to that contains the display text. We’ll call the signal ‘contentChanged
  • A signal from the UI to the engine when the “clear” button has been pressed. We’ll call the signal ‘clear
  • Something that sets up a connection from each button to the main ‘data‘ signal.

Let’s start with just the data signal. When you declare a signal (named ‘foo‘) then there is automatically a slot created called ‘onFoo‘).[5] Not only that, but if the signal was declared with an argument, the argument (and its name) is assumed when you implement the slot. So, for data:

    signal data(string val);
    onData: {
	console.log("iRoot: " + val)

    /* ... */

    /* Component.onCompleted() is more or less a constructor */
    Component.onCompleted: {

This is pretty simple… create the signal ‘data‘, on the slot log which button was pushed, and connect the signal/slot in the Component.onCompleted constructor-like-slot.

So, we finish out the design by implementing them all. All the slots will do something, just so that we get an indication that they are firing correctly. Building on top of Calculator.01.qml:

--- Calculator.01.qml
+++ Calculator.qml
@@ -1,5 +1,5 @@
 /*                                      -*- mode:javascript -*-
- * Calculator.01.qml - Uses the Button element.
+ * calculator.qml
  * This code was written by Gabriel M. Beddingfield <>
  * in 2011.  It is placed in the public domain.
@@ -14,6 +14,28 @@
     anchors.margins: 5;
     property string text: "0";

+    signal data(string val);
+    onData: {
+	console.log("iRoot: " + val)
+	contentChanged(val);
+    }
+    signal contentChanged(string val);
+    onContentChanged: {
+	if (text == "0") {
+	    text = val;
+	} else {
+	    text += val;
+	}
+    }
+    signal clear;
+    onClear: {
+	text = "0";
+    }
     Rectangle {
 	id: iDisplay;
 	color: "white";
@@ -69,5 +91,23 @@
 	Button { id: iC; text: "C"; }
 	Button { id: i0; text: "0"; }
 	Button { id: iPlus; text: "+"; }
+    }
+    /* Component.onCompleted() is more or less a constructor */
+    Component.onCompleted: {
+	/* N.B. Using 'iRoot.' here is redundant. */
+	iC.postValue.connect(iRoot.clear);
+	iPlus.postValue.connect(;
+	i0.postValue.connect(;
+	i1.postValue.connect(;
+	i2.postValue.connect(;
+	i3.postValue.connect(;
+	i4.postValue.connect(;
+	i5.postValue.connect(;
+	i6.postValue.connect(;
+	i7.postValue.connect(;
+	i8.postValue.connect(;
+	i9.postValue.connect(;

The temporary code is just to make the Calculator semi-functional, until we put the real brains into it. Try it out like this:

      $ qmlviewer Calculator.qml

Note that we could extend the prototype by adding JavaScript application logic (like several of the Qt Quick examples). However, since the goal is to connect a C++ engine to a QML UI, this would be a waste of time.


You might be asking, “where’s the C++ code?” We’ll do that next time. Hopefully, you can already see that we’ve set up a well-defined interface that we can use to connect our calculator brains to.

The biggest things that I learned in this part of the exercise are:

  • When making a custom component, it is generally better to use ‘Item’ as the base element of your component.
  • Use the Component.onCompleted method do internal signal/slot connections and any other init code.
  • Signals in QML will also implicitly create a slot. The slot function has some special “magic” in the way it is declared and over-ridden.
  • The scope of variables, properties, and id’s is kind of sloppy. Judicious use of Hungarian notation and object dereferences can make the code more readable.

Source Files

Button.qml — The Button abstraction.

Calculator.00.qml — The first Calculator iteration (layout)

Calculator.01.qml — The second Calculator iteration (using Button)

Calculator.qml — The final Calculator

[1] See the file 00_scaffolding.qml

[2] See Getting Started Programming with QML and Qt Quick …which also contains links to examples.

[3] “thingamajig.trigger()” — what the heck is “thingamajig???”

[4] I could have done it with width/height, too.

[5] If you, like me, don’t like camelCasing, getUsedToIt.


QtQuick: Why bother with QML?

December 21, 2011

This post is an introduction to the next several posts. If you’re bored with QtQuick introductions (since there are many)… then there’s probably nothing to see here.

Composite (and its ancestor Hydrogen) has always had a Qt UI. And when it comes to GUI, Qt is the toolkit that I prefer to use. Why Because I really don’t like UI development. I like to work on models, business logic, complex calculations, etc. I really get bored with sizing widgets and trying to figure out how to convince the font system to give you the real, actual, true bounding rectangle (and not the one that’s better for typesetting).

And then there’s the code. The options have always been something like:

  • Use a C API like GTK+ and write gobs of code and manually
    type all the gtk_widget_* namespaces for every class method.
  • Use a C++ API wripper like gtkmm (which never really gets
    rid of the smell of the C API).
  • Write gobs of Qt code to express your UI. Which means that
    small changes (like moving a widget from here to there) often
    require a lot of code changes.
  • Use a UI designer to create XML files that get processed into
    code. (I.e. Qt Designer or Glade.) While it’s easy, these
    files often have compatibility issues even across minor
    releases. They also are not very diff friendly (which is
    important to a backend-loving code monkey like me).
  • Write your UI in a scripting language like Tcl/Tk or Python
    (e.g. the PySide bindings). Here you trade-off flexibility
    for simplicity a lot of the time. (Think: custom widgets.)

These options all have one thing in common: they suck.

Along comes QtQuick, with the idea of expressing your UI in a scripting language called QML. QML is:

  • Like javascript and CSS: so it looks like code, and diff’s like code.
  • Declarative/Interpretive: so small changes just require that I refresh the QML file in question… not recompile (or even restart) my whole application.
  • Designer-friendly: if your project has an artist, they probably aren’t very good at C++. QML isn’t too difficult to parse… which makes them more productive.
  • Developer-friendly: as a C++ lover I’m not crazy about the syntax of QML… but I love that I can throw up a UI pretty quick. While the UI’s that I design look like butt… I don’t feel like I have invested a lot of code into something that needs to change (and change a lot) later in the project.
  • Architecture-friendly: It more or less enforces that you use a model/view architecture in your application. When the UI was code, it’s very tempting to pragmatically break the rules.
  • Prototype-friendly: You can add some logic into the QML via JavaScript, which means you can prototype the UI’s behavior without having to invest any C++ code.
  • Promising: The Qt framework is reorganizing itself around QML. It’s pretty fast now, but it promises to be blazing fast in Qt 5. (Even faster than using native widgets or QGraphicsView… and that’s an impressive accomplishment.)

However, it does come with a few drawbacks:

  • It’s oriented to embedded devices that have a fixed-size, full-screen “app” paradigm. Therefore, you’ll find that lots of sizes and relationships are set in fixed-size pixels. It’s not quite as nice as QLayout in C++. This means it’s still a little… primative in a desktop context.
  • The scripting language is kind of… strange. It is very weakly typed (e.g. inspecting the code you can’t be sure if a symbol is a property or a method or a signal or an element or a reference to a C++ class). This is really, really confusing.
  • The language uses a sort of “inner class” idiom like in Java.
  • It’s interpreted, so typos likemy_symbol/mySymbol will not be detected until run-time. (In fact, this is a drawback of Qt signals/slots as a whole.)
  • Concepts like QAction and QMenu are missing, and will probably never be added. They’ve been branded as obsolete, old thinking with respect to UI design. While I don’t necessarily disagree… the loss of them takes some getting used to.
  • It’s new, and the documentation is still developing. For example, none of the examples that I could find show any sort of in-depth C++/QML interaction. Most of the examples use JavaScript to implement the application logic.

All in all, I think that the good out-weighs the bad.

Since I don’t know how to use QML effectively, the following few blogs will share my journey and what I’ve learned. I’ll do so by writing a very simple calculator application.

That’s also the caveat: I’m writing this as I go… so I probably just said something dumb. 🙂

In seeking to continue Composite development, I needed a multi-touch environment.  All along, I figured that MeeGo would be that environment.  But the death of MeeGo means that this is no longer an attractive option.  I could do it, but it would be a stagnant OS, forever stuck at release 1.2.0.  I don’t want this for a development environment.

But as far as I know, MeeGo is still the only distro that gives you an out-of-the-box multi-touch experience.

Whatever distro I choose, I’ll need to fiddle with the Qt and Xorg packages on the system.  This is best done by creating new packages to replace the system ones (just in case you mess everything up, you can just revert back the package).  I chose Fedora because it tracks upstream projects very well, and also because I find RPM packaging much more enjoyable than DEB packaging.[2]

Here’s how I got a multi-touch-enabled Qt installed and working on Fedora 16.  I installed the 64-bit OS on my IdeaPad, so replace “x86_64” with “x86” if you’re using the 32-bit version.


If you don’t know how to install a Linux distro, fire off commands on a command line, or boot to single-user mode and fix a couple things — then this will probably be too much for you to take on. (E.g. if you just Googled “single-user mode” — STOP NOW! :-))

After installing Fedora 16, you need to set it up for building rpms. I didn’t keep good notes during this phase, so this is probably not complete:

    $ sudo yum groups install \
        "Development Tools" \
        "X Software Development"
    $ mkdir ~/rpmbuild
    $ cd ~/rpmbuild

Building the MTEV driver

The X11 input driver “mtev” is an interim solution to get multi-touch onto Linux devices like the N900, WeTab, N950, N9, etc. When XInput 2.2 finally hits the main-stream with a matching evdev driver, it will be obsolete.[4]

First, grab the sources and install the mtdev library:

    $ cd ~/code
    $ git clone git://
    $ sudo yum install mtdev-devel

Note that the tarball you need is already in the repository. Also, this has been modified to (a) compile with the 1.11 xserver and (b) it includes my right-click-emulation patch. If you don’t like it… choose the version you want with git.

Build it like this:

    $ cd ~/rpmbuild
    $ cp -f ~/code/xorg-x11-drv-mtev/* SOURCES/
    $ mv -f SOURCES/xorg-x11-drv-mtev.spec SPECS/
    $ rpmbuild -ba SPECS/xorg-x11-drv-mtev.spec 2>&1 | log-50

It only takes a few seconds to build. Then you can install it like this:

    $ sudo rpm -Uvh RPMS/x86_64/xorg-x11-drv-mtev-0.1.13-10.0.x86_64.rpm

Building Qt with Multi-Touch

On my IdeaPad, Qt takes about 9 or 10 hours to compile.  If you have a fast machine with F16, I recommend doing it there.

Start by checking out my source repository and grabbing the Qt sources that you need.  (Note, if the URL’s are cut off in your browser… there are links near the end of the article.  See “Resources.”)

    $ mkdir ~/code
    $ cd ~/code
    $ git clone git://
    $ cd fedora-pkg-qt
    $ git checkout topic/multitouch-00
    $ wget
    $ wget
    $ wget">hi48-app-qt4-logo.png

Now you can build it like this:

    $ cd ~/rpmbuild
    $ cp -f ~/code/fedora-pkg-qt/* SOURCES/
    $ mv -i SOURCES/qt.spec SPECS/
    $ rpmbuild -ba SPECS/qt.spec 2>&1 | tee log-00

Chances are that rpmbuild will choke on you, saying that you’re missing several required packages. You will need to install those. For example if it says that it needs “pkgconfig(foo)”, you can install it like this:

    $ sudo yum install "pkgconfig(foo)"

When done, install the packages in RPMS/. You probably want to do this:

    $ cd RPMS/x86_64/
    $ sudo rpm -Uvh qt{,-x11,-examples,-devel,-demos}-4.8.0-1.1.fc16.x86_64.rpm

To see which Qt packages you already have on your system, do:

    $ rpm -qa | grep qt

You only need to replace the ones that have a “4.8.0” version.

Verifying that it works

Reboot your computer and verify that it works. Run:

    $ /usr/lib64/qt4/examples/touch/fingerpaint/fingerpaint

If you can use 2 fingers to draw, then you are good to go! 🙂


X11 Fails to Start

If you reboot to a black screen, chances are that the MTEV driver is not kosher. Reboot to single-user mode and uninstall it.

    $ rpm -ev xorg-x11-drv-mtev

If you want to debug this… go right ahead. Chances are that its a failure in the driver’s PreInit() or something. However, I’m not going to be able to support you much with this.

No Multi-Touch

Do not be alarmed! Because this is driver is kind of a hack, you have to explicitly declare that the device should be managed by the mtev driver. xorg.conf.d files are installed for Cando, Sitronix, Hanvon, and ILI touchscreens. You might have a different one.

You can find out for sure by inspecting /var/log/Xorg.0.log. You should see something like:

[    26.125] (II) Using input driver 'mtev' for 'Cando Corporation Cando 10.1 Multi Touch Panel with Controller'

This was arranged by the /etc/X11/xorg.conf.d/60-cando-mtev.conf file, which looks like this:

Section "InputClass"
        Identifier              "Cando Multi Touch Panel"
        MatchVendor 		"Cando"
        MatchDevicePath 	"/dev/input/event*"
        Driver                  "mtev"
        Option                  "Ignore"                "off"

Your touchscreen device will need a different Identifier and MatchVendor string. Inspect your /var/log/Xorg.0.log for clues.

Using Right-Click Emulation

Open up the terminal application. Put one finger down and hold it. Now tap the screen with a second finger. The context menu will pop up. This gesture is easier (at first) if you use two hands.


Here are links to (most of) the resources that we used above.

[1] The Xorg devs think this will end with the release of F17.  XInput 2.2 is in the review process to be added to xserver 1.12.  However, I’ve heard that Qt will not add official support for it, instead waiting for Wayland.

[2] I cut my teeth on DEB.  For MeeGo I had to learn RPM, and found that I liked it better.  Less time tracking down opaque debhelper issues and DEB styles.

[3] I don’t know where the original files were served up, these links are to a cached copy at Fedora.  You can also get it from their qt SRPM.

[4] …presuming that someone actually breaks down and adds support to Qt. Otherwise, it’s still useful for Qt dev.