<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Spells from the Qt Wizard</title>
	<atom:link href="http://www.fioniasoftware.dk/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.fioniasoftware.dk/blog</link>
	<description>Fionia Software Qt Blog</description>
	<lastBuildDate>Wed, 25 Apr 2012 11:53:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Encapsulation in QML Components</title>
		<link>http://www.fioniasoftware.dk/blog/?p=173</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=173#comments</comments>
		<pubDate>Wed, 25 Apr 2012 11:53:40 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[QML]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=173</guid>
		<description><![CDATA[In QML, it&#8217;s so easy to use properties of components directly, and it&#8217;s even the way most examples do it. But here&#8217;s my quesion: If we consider this the wrong approach in C++, isn&#8217;t it wrong in QML as well? &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=173">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In QML, it&#8217;s so easy to use properties of components directly, and it&#8217;s even the way most examples do it. But here&#8217;s my quesion: If we consider this the wrong approach in C++, isn&#8217;t it wrong in QML as well? The answer is usually yes.</p>
<p>Here, I&#8217;ll show you how I think the best practice of building QML components is. It seems so simple, maybe even trivial. But I have met a lot of code that doesn&#8217;t follow it, and seen the problems that follow. QML is still so new, that best practice isn&#8217;t common knowledge. And in many cases, best practice haven&#8217;t even been discovered yet.</p>
<p>Let me give a quick example that shows the problem: You have created a Button component with all the bells and whistles such a component needs. You chose to build it using a Rectangle, so the border is handled by an existing component. Reuse is always a good and popular choice.</p>
<p>Here is some of the code of how the Button could be done:</p>
<pre>
Button.qml:
Rectangle {
    id: button
    border.width: 1
    signal clicked()
    property alias text: buttonText.text
    Text {
        id: buttonText
        anchors.centerIn: parent
    }
    ...
}
</pre>
<p>You now declare a Button, set the size and the text, and that&#8217;s it. However, you might also want to have a different border, so this is what we do in the UI QML file:</p>
<pre>
Ui.qml:
Rectangle {
    width: 360
    height: 360
    Button {
        anchors.centerIn: parent
        text: "Hello World"
        width: 100
        height: 30
        border.width: 2
        border.color: "blue"
    }
    ...
</pre>
<p>Now, here&#8217;s the problem: If you decide to expand the Button with other choices of how it can look, you will have a problem. For example, you might want to offer a BorderImage for the way the Button looks. But with the current use of a Rectangle, you can&#8217;t do this without modifying the code that uses this Button.</p>
<p>This is exactly the problem encapsulation solves: It allows you to make local changes to your component without modifying all the code that uses it.</p>
<p>The simple solution of the Button is to make it an Item that has a Rectangle. In OO terms, this changes from inheritance to aggregation.</p>
<p>My solution for creating QML components is to nearly always base them on Item, and expose whatever properties I want. The interface to my components is the sum of properties, functions and signals. How I choose to implement the component itself is an implementation detail, and should not be available to other components.</p>
<p>For a simple example, suppose we have a system where a bunch of Text items should always follow a shared style. If the style changes, all text must follow. In fact, the only thing the users of the text item can set, is the text itself.</p>
<p>This could clearly be done with Text directly:</p>
<pre>
StyledText.qml:
Text {
    // Event handlers to set the Style parts here:
    ...
}
</pre>
<p>This a valid choice, we simply need to tell ourselves that we shouldn&#8217;t set the color, size etc. directly, but allow the central style code to set it. And this is of course doomed. Some day, we hire a new coder, or forget ourselves. Whatever the reason, we will break the rules.</p>
<p>The proper solution is to encapsulate the component and hide the implementation behind the Item:</p>
<pre>
StyledText.qml:
Item {
    property alias text: textItem.text
    Text {
        anchors.fill: parent
        // Event handlers to set the Style parts here:
        ...
    }
}
</pre>
<p>It seems so simple, but I have seen a bunch of QML code that doesn&#8217;t do this. Every time you start modifying the code of components, you wonder what you break. And this only becomes much more valuable with real components that have much more complexity than the simple example code I have here.</p>
<p>If you follow this pattern instead, you will create robust and encapsulated components with no properties accessible by accident.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=173</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QObject SignalBlocker</title>
		<link>http://www.fioniasoftware.dk/blog/?p=158</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=158#comments</comments>
		<pubDate>Thu, 12 Jan 2012 08:13:09 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Qt]]></category>
		<category><![CDATA[Qt tricks]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=158</guid>
		<description><![CDATA[Sometimes you have to stop a class from emitting a signal for a while. One example that just came up on the Qt interest list was an application that modifies a file which it also monitors with a QFileSystemWatcher. You &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=158">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sometimes you have to stop a class from emitting a signal for a while. One example that just came up on the Qt interest list was an application that modifies a file which it also monitors with a QFileSystemWatcher. You usually don&#8217;t want a fileChanged signal when the modification comes from your own application.</p>
<p>The solution is quite standard and have been published in other blogs as well. But all of those I&#8217;ve seen miss one or two features. Which is quite a lot for a class this small. And this is also a cute little test for some nice Qt code, so I thought I&#8217;d publish my own version of this class.</p>
<p>The basic idea is simple, you want to have an object that controls blocking signals. So the code you write will be something like this:</p>
<pre>
{
    SignalBlocker blocker(targetObject);
    targetObject-&gt;doSomethingThatEmitsASignal();
}
</pre>
<p>Sometimes people ask why not just do the following?</p>
<pre>
targetObject-&gt;blockSignals(true);
targetObject-&gt;doSomethingThatEmitsASignal();
targetObject-&gt;blockSignals(false);
</pre>
<p>There are three problems with this. The first problem is that the signals might already be blocked, and this code will unblock them. This is one of the problems most SignalBlocker implementations I&#8217;ve seen miss.</p>
<p>The second problem is that <code>doSomethingThatEmitsASignal()</code> might throw an exception. If this happens, the signals will stay blocked. But with an object, the destructor will be called even in the case of an exception.</p>
<p>Finally, the <code>doSomethingThatEmitsASignal()</code> could end with <code>delete this</code>, so the code doing the unblocking must handle the case where the target object has been deleted. QPointer is the right solution for this, since it listens to the <code>destroyed()</code> signal. And no, that is never blocked. This problem is also not caught by the SignalBlocker implementations I&#8217;ve seen.</p>
<p>So the full SignalBlocker implementation should be something like this:</p>
<pre>
/**
 * Small helper class that blocks all signals from an object for the lifetime of this object.
 * it is safe against deletion of the object before deletion of this.
 *
 * This class was written by Bo Thorsen of Fionia Software &lt;bo@fioniasoftware.dk&gt;.
 * The code is in the public domain.
 */
class SignalBlocker {
public:
    explicit SignalBlocker(QObject* object) : mObject(object) {
        mWasBlocked = object-&gt;signalsBlocked();
        object-&gt;blockSignals(true);
    }

    ~SignalBlocker() {
        if (mObject &#038;&#038; !mWasBlocked)
            mObject-&gt;blockSignals(false);
    }

private:
    // Disabled
    SignalBlocker(const SignalBlocker&#038;);
    SignalBlocker&#038; operator=(const SignalBlocker&#038;);

    QPointer&lt;QObject&gt; mObject;
    bool mWasBlocked;
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=158</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QThread/QThreadPool Benchmarking</title>
		<link>http://www.fioniasoftware.dk/blog/?p=147</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=147#comments</comments>
		<pubDate>Thu, 20 Oct 2011 09:29:03 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=147</guid>
		<description><![CDATA[Here is the summary of the text below: Thread pools are superior. Which is hardly surprising, but now I have numbers to back it up. You can download the benchmark code I wrote from my website. The last couple of &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=147">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here is the summary of the text below: Thread pools are superior. Which is hardly surprising, but now I have numbers to back it up. You can download the benchmark code I wrote <a href="http://fioniasoftware.dk/freebies.html">from my website</a>.</p>
<p>The last couple of months have been spent with heavily multithreaded Qt code. Fun, yes, but also challenging. I have always had three rules about multithreading: 1: Don&#8217;t do it! 2: Don&#8217;t do it! 3: Don&#8217;t do it yet. Threaded code is harder to build and debug, and with event driven applications you rarely need to use it.</p>
<p>But in some cases multithreading is necessary. One example was my last customer. They had an application that had threads talking to hardware. This is a perfectly good example of something that certainly fits well in a separate thread.</p>
<p>When the hardware did something, they generated a work request. This was a QThread subclass that they called start on, and let it do it&#8217;s thing, and deleted the thread on completion. Not an unreasonable approach, but as they were generating around 10 threads per second, I did not like it. This is a textbook example of what QThreadPool is for.</p>
<p>I made a change on some of the work requests so they used QThreadPool instead. The modification to the code is minimal. Instead of subclassing QThread, they should subclass QRunnable. And then QThreadPool should run and delete the thread instead of the thread itself handling that.</p>
<p>First results were surprising: The work request time increased instead of going down. I told them not to worry, because the time of an individual request is not really what is interesting, the effect on the whole system is more important. In some use cases this is not true, but the new work request time handling was still well within their requirements.</p>
<p>So, the question remains whether I was right or not. Will a thread pool implementation use less total cpu time than a QThread based implementation? To answer this question, I wrote a small test benchmark. The code is very simple, but it does produce a pretty heavy load when run. As mentioned above, you can download it <a href="http://fioniasoftware.dk/freebies.html">here</a>.</p>
<p>Each work request makes a list of 1000 integers and then sorts them. Simple piece of work, and not something the compiler can do any tricks on. This simple function is just called by my QThread and QRunnable subclasses in the <code>run()</code> method.</p>
<pre>
static QList&lt;int&gt; doWork() {
    QList&lt;int&gt; numbers;

    // Fill the list with some numbers
    const int numberSize = 1000;
    int currentNumber = 0;
    for (int i = 0; i &lt; numberSize; ++i) {
        currentNumber = (currentNumber + 367) &amp; 1023;
        numbers &lt;&lt; currentNumber;
    }

    qSort(numbers);
    return numbers;
}
</pre>
<p>The tests do a number of iterations and on each iteration creates a number of threads and then goes to sleep for a bit, giving the worker threads some time for their work. With the numbers below, all was run with creating 25 worker threads on each iteration and sleeping for 10ms between each iteration. At the end, the QThread implementation deletes all the thread instances because QThreadPool does this automatically.</p>
<p>This is the loop that creates the worker threads and executes them. After this code, it deletes the threads and waits for all of them to finish.</p>
<pre>
void ThreadStarter::run() {
    QList&lt;QThread*&gt; threads;
    threads.reserve(mIterations * mThreadsPerIteration);

    for (int i = 0; i &lt; mIterations; ++i) {
        for (int t = 0; t &lt; mThreadsPerIteration; ++t) {
            if (mType == Thread) {
                WorkThread* thread = new WorkThread;
                thread-&gt;start();
                threads &lt;&lt; thread;
            } else {
                WorkRunnable* runnable = new WorkRunnable;
                QThreadPool::globalInstance()-&gt;start(runnable);

                // Mimic the same work as with threads
                threads &lt;&lt; 0;
            }
        }

        msleep(mSleepTime);
    }
    ...
</pre>
<p>I ran this with a growing number of iterations. The table below shows the number of iterations, the time for the thread based implementation to run, and finally the time for the threadpool implementation:</p>
<pre>
i: 10 thread ms: 107 runnable ms: 102
i: 20 thread ms: 215 runnable ms: 206
i: 30 thread ms: 322 runnable ms: 311
i: 40 thread ms: 429 runnable ms: 407
i: 50 thread ms: 546 runnable ms: 507
i: 60 thread ms: 651 runnable ms: 610
i: 70 thread ms: 765 runnable ms: 713
i: 80 thread ms: 860 runnable ms: 812
i: 90 thread ms: 966 runnable ms: 912
i: 100 thread ms: 1084 runnable ms: 1022
i: 110 thread ms: 1181 runnable ms: 1119
i: 120 thread ms: 1289 runnable ms: 1218
i: 130 thread ms: 1404 runnable ms: 1318
i: 140 thread ms: 1505 runnable ms: 1420
i: 150 thread ms: 1624 runnable ms: 1521
i: 160 thread ms: 1722 runnable ms: 1622
i: 170 thread ms: 1842 runnable ms: 1728
i: 180 thread ms: 1944 runnable ms: 1823
i: 190 thread ms: 2043 runnable ms: 1924
</pre>
<p>As you can see, the conclusion is completely clear: In every case, the thread pool implementation is faster than the QThread implementation. So even though each worker thread could finish faster with the thread implementation, the total system time is higher. This is relevant when the machine gets heavily loaded (as it did for my customer), because then you need the threads to take up as little total time as possible.</p>
<p>I have run this with other numbers of threads generated and sleeping time, and on different machines. The conclusion have always been the same. Not a single time has the QThread approach been the fastest.</p>
<p>There is another benefit to the thread pool based approach that has nothing to do with speed. This is the problem of deletion of the worker threads. It&#8217;s not trivial to figure out how to delete the thread object, once it&#8217;s done. Of course, a connect from <code>finished()</code> to <code>deleteLater()</code> usually does the trick. Unless you do something like <code>thread->moveToThread(thread)</code> and call <code>exec()</code> in the run method. With the thread pool approach it&#8217;s trivial, since the pool will by default just delete the worker thread object when it&#8217;s done.</p>
<p>So, my recommendation stands: Unless you have a really good reason not to, you should use a thread pool for worker threads.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=147</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing tool tips in QML</title>
		<link>http://www.fioniasoftware.dk/blog/?p=142</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=142#comments</comments>
		<pubDate>Sat, 17 Sep 2011 07:10:13 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[QML]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=142</guid>
		<description><![CDATA[If you are using the Qt Components, you have tool tips available. But with the standard SDK, you&#8217;re on your own. Here, I&#8217;ll implement a simple tool tip component for you. In my application, I have a lot of Text &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=142">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you are using the Qt Components, you have tool tips available. But with the standard SDK, you&#8217;re on your own. Here, I&#8217;ll implement a simple tool tip component for you.</p>
<p>In my application, I have a lot of Text objects that have the same font, color etc. so I have put those in a TTText.qml. In this, I also have the tool tip property, which is the only thing I will show here:</p>
<pre>
import QtQuick 1.0

Text {
    property string toolTip
    // ...
    ToolTip { toolTip: parent.toolTip }
}
</pre>
<p>The idea here is simply to have a toolTip property directly on the TTText object. I could have chosen to use it with <code>myText.toolTip.text</code> instead, but by using a property directly on the Text object, I have encapsulated the tool tip inside it.</p>
<p>First attempt at a ToolTip.qml is a very simple one:</p>
<pre>
import QtQuick 1.0

Item {
    anchors.fill: parent

    property string toolTip
    property bool showToolTip: false

    Rectangle {
        id: toolTipRectangle

        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.bottom
        width: toolTipText.width + 4
        height: toolTipText.height + 4
        z: 200

        visible: toolTip != "" &#038;&#038; showToolTip

        color: "#ffffaa"
        border.color: "#0a0a0a"

        Text {
            id: toolTipText
            text: toolTip
            color: "black"
            anchors.centerIn: parent
        }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onEntered: showToolTip = true
        onExited: showToolTip = false
        hoverEnabled: true
    }
}
</pre>
<p>The MouseArea is the first piece needed. This is the part that tells when the user hovers the mouse over the text. When this is the case, it sets the <code>showToolTip</code> to true, which the tool tip rectangle uses to know when it should show itself.</p>
<p>This is actually enough to have working tool tips on your items. But it&#8217;s a bit rough: It just goes visible as soon as the mouse enters the item holding the ToolTip.</p>
<p>First thing I want to add is a fade in and fade out. I do this by changing the viewing of the tool tip from using the <code>visible</code> property to the <code>opacity</code> and do an animation on the property changes.</p>
<p>The second thing is that I want the tool tip to wait a bit before it pops up, so it doesn&#8217;t show itself when I just move the mouse over the holding item. This is done with a timer that is started by the MouseArea enter event. When the timer fires, it sets the opacity to 1.</p>
<p>With these two changes we have a nice and usable tool tip item. If you want to, you can add properties to change the way the tool tip looks, the timer duration or the animation duration etc.</p>
<p>Here is the final version:</p>
<pre>
import QtQuick 1.0

Item {
    anchors.fill: parent

    property string toolTip
    property bool showToolTip: false

    Rectangle {
        id: toolTipRectangle

        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.bottom
        width: toolTipText.width + 4
        height: toolTipText.height + 4
        z: 200

        opacity: toolTip != "" &#038;&#038; showToolTip ? 1 : 0

        color: "#ffffaa"
        border.color: "#0a0a0a"

        Text {
            id: toolTipText
            text: toolTip
            color: "black"
            anchors.centerIn: parent
        }

        Behavior on opacity {
            PropertyAnimation {
                easing.type: Easing.InOutQuad
                duration: 250
            }
        }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onEntered: showTimer.start()
        onExited: { showToolTip = false; showTimer.stop(); }
        hoverEnabled: true
    }

    Timer {
        id: showTimer
        interval: 250
        onTriggered: showToolTip = true;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=142</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom positioners in QML</title>
		<link>http://www.fioniasoftware.dk/blog/?p=124</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=124#comments</comments>
		<pubDate>Sun, 04 Sep 2011 08:00:49 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[QML]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=124</guid>
		<description><![CDATA[If none of the four standard positioners (Column, Row, Flow, Grid) work for you, you can write your own. I have a pet project that involves a poker table. This is done with a list model that has a list &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=124">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If none of the four standard positioners (Column, Row, Flow, Grid) work for you, you can write your own.</p>
<p>I have a pet project that involves a poker table. This is done with a list model that has a list of seats with the name, stack size etc. exposed as custom roles. In this example, I only use the &#8220;name&#8221; role in a Text item. The real application has a Seat custom item that uses all the roles.</p>
<p>I have a C++ implementation of the table (exported to the QML as PokerTable in the Poker module), which draws the table and calculates the seat positions. My goal now is to create the seat items on the correct positions. There is another C++ class that implements the hand model.</p>
<p>The first step is to just show that the model works. I do this with the standard Row positioner and a Repeater for the model:</p>
<pre>import QtQuick 1.0
import Poker 1.0

Item {
    PokerTable {
        id: table
        anchors.fill: parent

        Row {
            anchors.centerIn: parent

            Repeater {
                model: handModel
                Text { text: name }
            }
        }
    }
}</pre>
<p>With this simple QML, I can see my table with the player names placed next to each other in the center of the table. So far so good.</p>
<p>Next step is to implement a simple positioner, that shows how this actually works:</p>
<pre>import QtQuick 1.0
import Poker 1.0

Item {
    PokerTable {
        id: table
        anchors.fill: parent

        Item {
            id: seatView

            anchors.fill: parent

            onChildrenChanged: updatePositions();

            Repeater {
                model: handModel
                Text { text: name }
            }

            function updatePositions() {
                for (var i = 0; i &lt; seatView.children.length; ++i) {
                    seatView.children[i].pos = Qt.point(i * 50, i * 5);
                }
            }
        }
    }
}</pre>
<p>This code calculates the positions for each of the seats, when children are added or removed. The position calculations do not make any sense, they just show an effect where you can be sure that it works.</p>
<p>In my case, I want the table class to calculate the seat positions, because I don&#8217;t want to copy those calculations to another place. But it might be that the above code pattern is all you need to implement your own positioner, if you can code it in javascript.</p>
<p>A couple of final touches are also needed. First, I&#8217;ll add (but not show here) a signal from the table class that can be emitted when the positions change for other reasons &#8211; resizing, for example.</p>
<p>The <code>updatePositions()</code> function will be called every time a child is added. I can have ten seats, so my function will be called when the first child have been added, then when the second, etc. That means it&#8217;s a bad idea to do the real calculations when new seats will be added immediately after. There are several ways to fix this. You could add a zero time timer that is restarted when the signal fires and will run the update function as it&#8217;s done. In my case, I already have the seat count exported as a property on my table, so I&#8217;ll check that the seat count is the same as the number of children before doing any work.</p>
<p>You might need to handle that the repeater is also a child of the view. I do this by setting an object name on the repeater and skip this child.</p>
<p>For the actual positions of the seats, I add this function in my C++ table class:</p>
<pre>Q_INVOKABLE QPointF seatPosition(int seat) const;</pre>
<p>Now I can do the proper positioning in the QML slot:</p>
<pre>function updatePositions() {
    if (seatView.children.length == table.seats + 1) {
        var index = 0;
        for (var i = 0; i < seatView.children.length; ++i) {
            if (seatView.children[i].objectName != "repeater") {
                seatView.children[i].pos = table.seatPosition(index++);
        }
    }
}</pre>
<p>So there you have it, a simple custom positioner that you can modify to place the view items in any kind of positioning you want.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=124</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>QCalendarWidget on Symbian</title>
		<link>http://www.fioniasoftware.dk/blog/?p=94</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=94#comments</comments>
		<pubDate>Fri, 10 Jun 2011 09:51:06 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[Qt]]></category>
		<category><![CDATA[Symbian]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=94</guid>
		<description><![CDATA[QCalendarWidget is a date picker widget which works well on the desktop, but has issues on embedded devices. It is one of many widgets in Qt that was certainly built for desktop and completely forgotten for something like a Symbian &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=94">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>QCalendarWidget is a date picker widget which works well on the desktop, but has issues on embedded devices. It is one of many widgets in Qt that was certainly built for desktop and completely forgotten for something like a Symbian based C7.</p>
<p>Over the last month, I&#8217;ve been working for Swiss company <a href="http://www.poken.com">Poken</a>, implementing an application for the Nokia C7. It&#8217;s a great tool to &#8220;Collect people, places and things, with a touch&#8221; as they phrase it.</p>
<p>One of the things I had to do here was a simple task: Allow the user to set his birthday. Which naturally means using QCalendarWidget. The problem was that the navigation bar for choosing the year or month sucks on small touch screens. So I wrote a small class that uses QCalendarWidget but adds a usable chooser bar.</p>
<p>The DatePicker widget is shown in a modal dialog. The result can be seen in this screenshot (click for a larger image): <a href="http://www.fioniasoftware.dk/download/poken2.png"><img src="http://www.fioniasoftware.dk/blog/wp-content/uploads/2011/06/poken2-thumbnail.png" alt="" title="Poken screenshot" width="180" height="320" class="alignright size-full wp-image-112" /></a></p>
<p>The new bar is four buttons for changing the year and month and a label in the middle to show the current date. The code for it is very simple. The widgets are done in designer, and the code is pretty much just this:</p>
<pre>QDate DatePicker::currentDate() const {
    return ui->calendar->selectedDate();
}

void DatePicker::setCurrentDate(const QDate &#038;d) {
    QDate date = d;
    if (!date.isValid())
        date = QDate::currentDate();
    ui->calendar->setSelectedDate(date);
    ui->calendar->showSelectedDate();
    on_calendar_clicked(date);
}

// The other four buttons are handled the same way as this
void DatePicker::on_yearBackButton_clicked() {
    QDate date = currentDate();
    date = date.addYears(-1);
    setCurrentDate(date);
}

void DatePicker::on_calendar_clicked(const QDate &#038;date) {
    ui->dateLabel->setText(date.toString(Qt::SystemLocaleDate));
}</pre>
<p>This is a small and, admittedly, somewhat trivial problem. But the general problem of Qt being too desktop oriented is real. This blog entry is an attempt to show (without getting buried in code details) that if you get just a little bit creative, the Qt widgets still work well on embedded systems like the Nokia phones.</p>
<p>Thank you <a href="http://www.poken.com">Poken</a> for giving me permission to use their code as an example.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=94</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ctrl+Enter Edit Handling</title>
		<link>http://www.fioniasoftware.dk/blog/?p=84</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=84#comments</comments>
		<pubDate>Fri, 01 Apr 2011 07:24:52 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[Qt tricks]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=84</guid>
		<description><![CDATA[I have a pet project where I&#8217;m doing some fun stuff with Qt scripting. To quickly test small script things, I implemented a simple window that have a QPlainTextEdit where I input a script, and an output window for what &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=84">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have a pet project where I&#8217;m doing some fun stuff with Qt scripting. To quickly test small script things, I implemented a simple window that have a QPlainTextEdit where I input a script, and an output window for what the script returns. And of course a QPushButton I can push to have the script evaluated.</p>
<p>Switching to use the mouse to press the eval button is obviously completely unacceptable, so I had a standard keyboard shortcut on the eval button. However, it seems more and more &#8220;standard&#8221; to use Ctrl+Return in text edits when the edit is done and should be handled, so I found myself pressing this a couple of times.</p>
<p>Implementing this for QPlainTextEdit can be done in many ways. One would be to subclass it and handle the keyboard events directly. If you have to subclass it anyway, that&#8217;s a nice option. But in this case, the UI was done in designer and I wasn&#8217;t already subclassing it.</p>
<p>Another way would be to create an eventFilter. This is of course one of those &#8220;if you only have a hammer, all problems are just nails&#8221;. Event filters are so easy to use, very powerful and able to do the trick, and one of the biggest hammers you&#8217;ll find in Qt. In this case, I would implement a class like this:</p>
<pre>class CtrlEnterKeyPressFilter : public QObject {
public:
    CtrlEnterKeyPressFilter(QWidget* widget, QPushButton* button)
        : QObject(widget), mButton(button)
    {
        widget-&gt;installEventFilter(this);
    }

protected:
    bool eventFilter(QObject*, QEvent* event) {
        if ((event-&gt;type() == QEvent::KeyPress
                || event-&gt;type() == QEvent::KeyRelease) &#038;&#038; mButton)
        {
            // This might be one for us
            QKeyEvent *keyEvent = static_cast&lt;QKeyEvent*&gt;(event);
            if (keyEvent-&gt;key() == Qt::Key_Return &#038;&#038;
                    keyEvent-&gt;modifiers() == Qt::ControlModifier)
            {
                // Ctrl + return pressed
                if (event-&gt;type() == QEvent::KeyRelease) {
                    mButton->click();
                }

                // This event has been handled
                return true;
            }
        }

        return false;
    }

private:
    QPointer&lt;QPushButton&gt; mButton;
};</pre>
<p>However, my favourite way to implement this is to use a QAction and set a keyboard shortcut on that:</p>
<pre>QAction* action = new QAction(d-&gt;ui.input);
action-&gt;setAutoRepeat(false);
action-&gt;setShortcut(tr("Ctrl+Return"));
connect(action, SIGNAL(triggered()), d-&gt;ui.eval, SLOT(click()));
d-&gt;ui.input-&gt;addAction(action);</pre>
<p>This is a simple and clean solution that does the trick for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=84</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dynamic Language Change</title>
		<link>http://www.fioniasoftware.dk/blog/?p=75</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=75#comments</comments>
		<pubDate>Thu, 31 Mar 2011 07:29:28 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[FS Editor]]></category>
		<category><![CDATA[Locale]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=75</guid>
		<description><![CDATA[Should a language change happen immediately? I tend to prefer applications switching immediately. This blog post is about the tricks you need to do in Qt to support such a change, not whether or not it makes sense to do &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=75">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Should a language change happen immediately? I tend to prefer applications switching immediately. This blog post is about the tricks you need to do in Qt to support such a change, not whether or not it makes sense to do so.</p>
<p>All the code mentioned in this blog post is from my Qt example application <a title="FS-editor" href="../../fseditor.html" target="_blank">FS-editor</a>. This is a complete (but small) text editor implemented to show the code I talk about in this blog.</p>
<p>First of all, you have to implement a way for the user to choose the current language. This would normally be done in a preferences or settings dialog. In <a title="FS-editor" href="http://www.fioniasoftware.dk/fseditor.html" target="_blank">FS-editor</a>, I have just added a menu with the available languages, but for most applications that would be too prominent a position for such a rarely used set of actions.</p>
<p>Changing the current language is done by deleting the previously installed translator objects and loading the new ones. In <a title="FS-editor" href="../../fseditor.html" target="_blank">FS-editor</a> there is this function, that takes one of the language codes (en, da, etc.):</p>
<pre>void LibUI::Translation::installTranslator(const QString&amp; code) {
    QDir translationsPath(findTranslationsPath());

    const QList&lt;QTranslator*&gt; oldTranslators(findChildren&lt;QTranslator*&gt;());

    if (code == "en") {
        // English means no translator installed
        qDeleteAll(oldTranslators);
    } else if (translationsPath.isReadable()) {
        // Try loading the new translation
        QScopedPointer&lt;QTranslator&gt;
        appTranslator(new QTranslator(this));
        QScopedPointer&lt;QTranslator&gt;
        qtTranslator(new QTranslator(this));
        if (appTranslator-&gt;load("fseditor_" + code, translationsPath.absolutePath())
            &amp;&amp; qtTranslator-&gt;load("qt_" + code, translationsPath.absolutePath()))
        {
            // Delete the old translators
            qDeleteAll(oldTranslators);

            // Install the new ones
            QCoreApplication::instance()-&gt;installTranslator(appTranslator.take());
            QCoreApplication::instance()-&gt;installTranslator(qtTranslator.take());
        }
    }
}</pre>
<p>One thing to notice in this is that I load both my own translations and the Qt translations. The Qt translations handles all user visible strings from Qt &#8211; dialogs, for example.</p>
<p>Installing the new translators is not enough. You need to catch the language change for changing all the user visible strings. This should be done by listening to the LanguageChange event:</p>
<pre>void LibUI::MainWindow::changeEvent(QEvent* event) {
    if (event-&gt;type() == QEvent::LanguageChange) {
        languageChange();
    }
    QWidget::changeEvent(event);
}</pre>
<p>Using the changeEvent is the best way to avoid too tight coupling of code for receiving the information about a language change. I prefer this over a manual connect to a language switch signal, which in large applications will give you the dreaded spaghetti code.</p>
<p>When you have caught the language change, you need to update all your user visible strings. This means labels, buttons, tab text, window captions, etc. Every single string that the user can see has to be updated with a tr(&#8220;&#8230;&#8221;) call. The exception to this is modal dialogs, because the user doesn&#8217;t have access to the language switch when one of these is up. The exception to this exception could be the settings dialog, although I disagree that this dialog should be modal.</p>
<p>You also need to switch all keyboard shortcuts. You must never assume that there is the same set of shortcuts for other languages. And you should call retranslateUi on the designer generated code.</p>
<p>One final bit is fixing some of the Qt actions. In <a title="FS-editor" href="../../fseditor.html" target="_blank">FS-editor</a> I use the Qt undo/redo framework, and the text on the undo and redo actions does not automatically update itself on language change. I do this manually:</p>
<pre>QSharedPointer&lt;QAction&gt; action(d-&gt;undoGroup.createUndoAction(0));
d-&gt;undoAction-&gt;setText(action-&gt;text());
action = QSharedPointer&lt;QAction&gt;(d-&gt;undoGroup.createRedoAction(0));
d-&gt;redoAction-&gt;setText(action-&gt;text());
</pre>
<p>At startup time, you should figure out what language to show. If the user set this in the preferences, you should store and use this choice, of course. But on the first startup, it&#8217;s normal to try and load the language of the OS itself. A call to <code>QLocale::system().name()</code> will give you the language code to use. On my system, the editor starts up in Danish.</p>
<p>With all these steps implemented, you should have complete language switching done.</p>
<p>In <a title="FS-editor" href="../../fseditor.html" target="_blank">FS-editor</a>, you can see how all this is put together in a real application. The interesting bits (at least in this context) are found in the files source/libui/translation.cpp and source/libui/mainwindow.cpp.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=75</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Printing parts of an XML tree</title>
		<link>http://www.fioniasoftware.dk/blog/?p=70</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=70#comments</comments>
		<pubDate>Tue, 29 Mar 2011 08:51:42 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[Qt tricks]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=70</guid>
		<description><![CDATA[When debugging XML code, you often wonder about the contents of a subtree. If the tree is small, you can just print it. But when the XML tree gets big, this just isn&#8217;t very handy. Especially not if you are &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=70">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When debugging XML code, you often wonder about the contents of a subtree. If the tree is small, you can just print it. But when the XML tree gets big, this just isn&#8217;t very handy. Especially not if you are looking at the output through a small debug window.</p>
<p>To view the contents of a subtree, you can use this simple function:</p>
<p><code>void printDomNode(const QDomNode&#038; node) {<br />
    QDomDocument d("debugxml");<br />
    d.appendChild(node);<br />
    qDebug() << "Text XML:" << d.toString();<br />
}</code></p>
<p>You will get the open XML tag at first, but since this is for debugging purposes, I never bothered to write the code to get rid of it. This trick is so small that I don't have it stored anywhere, I just rewrite the function whenever I need to do it.</p>
<p>The only problem with this: It destroys the XML tree. Even though the node is a const ref, this code will still destroy the tree it comes from. I personally think this is a completely unacceptable Qt bug.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=70</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Getting rid of compiler warnings for Symbian</title>
		<link>http://www.fioniasoftware.dk/blog/?p=59</link>
		<comments>http://www.fioniasoftware.dk/blog/?p=59#comments</comments>
		<pubDate>Tue, 22 Mar 2011 10:11:18 +0000</pubDate>
		<dc:creator>Bo Thorsen</dc:creator>
				<category><![CDATA[Symbian]]></category>

		<guid isPermaLink="false">http://www.fioniasoftware.dk/blog/?p=59</guid>
		<description><![CDATA[If you download the Qt SDK from Nokia and compile for Symbian, you get an obscene amount of warnings. I&#8217;m really annoyed that Nokia thinks it&#8217;s acceptable to ship a package with this kind of problem. And talking to the &#8230; <a href="http://www.fioniasoftware.dk/blog/?p=59">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you download the Qt SDK from Nokia and compile for Symbian, you get an obscene amount of warnings. I&#8217;m really annoyed that Nokia thinks it&#8217;s acceptable to ship a package with this kind of problem. And talking to the Qt people doesn&#8217;t help, it sounds like they have given up on the Symbian crew that should fix these problems.</p>
<p>Some of these problems are actually serious. For example this one in e32cmn.inl:</p>
<p><code>inline SVendorId::operator const TVendorId&#038;() const<br />
	{ /* coverity[return_local_addr] */ return (const TVendorId&)iId; }</code></p>
<p>This returns a reference to a temporary. Nice.</p>
<p>The fix for the warnings in e32cmn.inl is to change the C-style warnings to this:</p>
<p><code>inline SVendorId::operator const TVendorId&#038;() const<br />
        { /* coverity[return_local_addr] */ return reinterpret_cast&lt;const TVendorId&&gt;(iId); }</code></p>
<p>It&#8217;s not pretty, but it&#8217;s silent.</p>
<p>After this, you have to remove a &#8220;/**&#8221; that is inside another comment, and comment out an empty enum declaration.</p>
<p>Finally, you have to add some compiler flags to get rid of the remaining warnings. In our current build, we have these lines in the .pro file:</p>
<p><code>symbian {<br />
    QMAKE_CXXFLAGS += -Wall -fdiagnostics-show-option -Wno-parentheses -Wno-invalid-offsetof -Wno-psabi -Wclobbered -Wempty-body -Wignored-qualifiers -Wmissing-field-initializers -Wsign-compare -Wtype-limits -Wunused-parameter<br />
}</code></p>
<p>The <code>-Wno-psabi</code> switch is only available on gcce 4.4.1. The first SDK version to ship this was 1.1-beta. If you have an earlier version, remove this flag.</p>
<p>With these fixes, the project I&#8217;m working on at the moment (<a href="http://www.poken.com">Poken</a>), compiles without a single warning from the SDK.</p>
<p>I normally only publish things on this blog that&#8217;s my own work. However, credit for most of this goes to Razvan and his <a href="http://blog.codeimproved.net/2010/06/getting-rid-of-the-nokia-qt-sdk-warnings">blog entry</a>. But the question of how to get rid of those compiler warnings keeps popping up everywhere, so I thought it was time to remind people. Also, it&#8217;s not possible to comment on his blog to add the parts he doesn&#8217;t have, so I have published an updated version of this. So please, keep in mind that this blog entry is really Razvans work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fioniasoftware.dk/blog/?feed=rss2&#038;p=59</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

