Sunday, September 4, 2011

Simple Singleton explanation

Hi there people,

I just spent one day trying to figure out why my C++ destruction sequence was creating a resource leak... This morning I noticed it came from one of my Singleton, the one behaving as my database manager.

So people, please be careful when using the Singleton Pattern, esp. when you access resources such as connections, or files.

Here is the thing:

In most cases, you can create a static class member pointing to the instance of your Singleton. This way is really easy to use but generates leak because the destructor is not clearly called. In fact, the memory de-allocation will be done by the OS once you exit your application. Here is the usual code.

// singleton.h
class Singleton
{
public:
    static Singleton* getInstance();
    // Other functions if needed
private:
    Singleton();
    ~Singleton();
    static Singleton* _singletonInstance;
};

// singleton.cpp
#include "singleton.h"

Singleton *Singleton::_singletonInstance = NULL;

Singleton*
Singleton::getInstance()
{
    if(!_singletonInstance){
        _singletonInstance = new Singleton();
    }
    return _singletonInstance;
}

Singleton::Singleton()
{
    // Do what you have to do
}

Singleton::~Singleton()
{
    // Do what you have to do
}

Note: you can see I'm using the lazy initialization to create the instance of my Singleton.

Anyway, this is a very easy and convenient way to have a global and unique instance... Of course, this assume that you do not really need to care about your singleton anymore.

However, if you really need the destructor to be called (e.g. to close a stream) then, it's better to have a simple static variable (no need to check its existence either, it will be created once and for all at the beginning of the application). In this case you can be sure that the destructor will be called. Here is the code:

// singleton.h
class Singleton
{
public:
    static Singleton* getInstance();
    // Other functions if needed
private:
    Singleton();
    ~Singleton();
    // No static class member here !
};

// singleton.cpp
#include "singleton.h"

Singleton*
Singleton::getInstance()
{
    static Singleton _singletonInstance;
    return &_singletonInstance;
}

Singleton::Singleton()
{
    // Do what you have to do
}

Singleton::~Singleton()
{
    // Do what you have to do
}

Of course, you can also do something like this if you want:

Singleton*
Singleton::getInstance()
{
    Singleton* pSingleton = NULL
    static Singleton _singletonInstance;
    pSingleton = &_singletonInstance
    return pSingleton;
}

Anyhow, this second way is much better in the case of a destruction sequence which needs to be clear. In fact, this solved my memory leak problem since with this second version of the Singleton, my destructor was correctly called and the connection to the database was correctly closed.

For your interest, this 2nd case is also called the Meyers' implementation of the Singleton, whereas the 1st one is the GoF implementation.

I hope it can be useful for some of you.

Saturday, September 3, 2011

ListModel in C++ exposed to QML

Hi there people,

I have been working a lot lately on my master thesis and I'm currently developing the prototype of my system. It's getting bigger and bigger, mixing Qt/C++ and QML/Javascript. So far, it's working like a charm.

One interesting behavior of my system is how my system is handling data. Indeed, I needed QML ListModels for my QML UI but I also needed some persistence... So of course I created a database... but since I need to access the database from the C++ side, I couldn't really use the Offline Storage capability of QML since the database generated in this case is randomly named... This would have been quite time wasting to try to access it... So, instead, I create my database with a database manager class written in C++. This database is a simple SQLite database.

At start up, I create several C++ ListModels which are populated from the database and that I link to the instance of the QMLApplicationViewer, this way I can access their data from my QML ListViews and GridViews. The C++ ListModel class that I use, is taken directly from here.

I owe Chris a big big thank for providing this implementation of a ListModel and for giving an example showing how to use the stuff. So Chris, if you read this blog entry, THANKS A LOT!!! :)

I will not explain how this works, Chris is doing that quite well on his own. Just check the given link. But, here comes the why of this blog entry. The implementation provided by Chris is somehow limited. In fact some interesting functionality which are provided in a normal QML ListModel such as count or get() are missing. I guess he let that task for us, or maybe he just didn't think someone would need it.

In my case, I needed to split one of these ListModel in 3 different sub models... I tried to use the QSortFilterProxyModel class but this didn't work... So I came up with another way to do it.

As you might all know (or might know soon by checking this link), when you create a class which is meant to be exposed to QML, you can provide functions which can be called from QML by giving the Q_INVOKABLE flag and QVariant can be understood by QML/Javascript. Also you can provide some variables which can be read from QML by creating a Q_PROPERTY. For the case of my exposed ListModel, I needed the count value and the get() functions, so I made them and here is the code to add to Chris's class:

In the .cpp
QVariant ListModel::get(int row)
{
    ListItem * item = m_list.at(row);
    QMap<Qstring, Qvariant> itemData;
    QHashIterator<int, Qbytearray> hashItr(item->roleNames());
    while(hashItr.hasNext()){
        hashItr.next();
        itemData.insert(hashItr.value(),item->data(hashItr.key()).toString());
    }
    // Edit: 
    // My C++ is sometimes a bit rusty, I was deleting item... 
    // DO NOT delete item... otherwise you remove the item from the ListModel
    // delete item;
    return QVariant(itemData);
}

To get the count.

In the .h
public ListModel : public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY( int count READ getCount() NOTIFY countChanged())

public:
    ...
    int getCount() { this->count = this->rowCount(); return count; }
    Q_INVOKABLE QVariant get(int row);
    ...
private:
    ...
    int count;
    ...
};

The get() function will create a QVariant which is like a Javascript object. So you can have later in your Javascript something like:

function useCppModel(){
    // We can check the number of item in our C++ Model now
    for(var i = 0; i < model.count; i++){
        // Here you use the get function declared as invokable
        // It's just like a real ListModel now ;)
        var item = model.get(i);
        // Now, you can then access the content of your item like item.property
    }
}

That's pretty much my addition to what Chris provided and this might inspire/help some of you. I hope you enjoyed. Sorry, if I'm not doing a complete tutorial, but I do not have much time.

P.S.: By the way, I'm now QtAmbassador. Yeah~ :D

EDIT: I corrected the bug with the first C++ code snippet.

Wednesday, June 8, 2011

Some news

Hi there QML fans,

I'm deeply sorry to tell you that at the moment, I'm extremely busy with my life. This means, no QML tutorial for awhile.

To tell you the truth, this beginning of the year was quite something! I actually did lot of things and still have lots to do:

I took part in the RoboCup@Home German Open 2011, in Magdeburg, Germany and with the team with reached the 2nd place.
I also spent some time to finish my 3rd semester of Master... Yeah, I had to learn for my exams, like any other student.
During my free time, I mainly co-developed a Dropbox Client for Symbian^3 devices (targeting N8, C7, E7, and similar) with a friend. Our application is called DropML. You can check our blog here. For the curious ones, it's Qt 4.7.3, mainly QML/Javascript but with some C++ too.

Currently, I'm doing my Master Thesis... Something about UI. I won't go deeper in details here.

Anyway, I'll do my best, I'll try to find some free time to make a new tutorial.

See you guys. :)

Sunday, February 13, 2011

Second QML Tutorial

Hi everybody,

Here is finally the second QML tutorial! Before starting, I hope you are all ok with the first tutorial, I hope you remember the first application with the circles. If not, you can find the link to the tutorial on the menu on your right.

So, now that you remember, you can see that several pieces of code have been repeated. Let’s have an example:
Rectangle{
    id: happy_circle_green
    x: 271
    y: 72
    width: 63
    height: 63
    radius: width/2
    color: "lightgreen"
}
As you already noticed, they all have the same properties, only the value is changing. However, this is not nice to write them all like a long list. This is not very efficient. A good design idea is to make things reusable. Then it’s more efficient, and you can even share components between applications when it’s possible.

Let’s create a new application called Second Tutorial. In your application folder, please add a file called Circle.qml. The capital letter at the beginning might look useless but it is said in the documentation that it’s a good practice and I actually like it like this. Also, regarding naming, here is another good practice: NO SPACE in file names. It’s better to use the underscore character.

Ok, so back to our new file, we can put the following code in it:
import QtQuick 1.0

Rectangle{
    id: circle_root

    property int posX: 0
    property int posY: 0
    property int size: 200
    property string selectedColor: "black"

    x: posX
    y: posY
    width: size
    height: size
    radius: size/2
    color: selectedColor
}
As you can see, I’m using a new important thing: the property keyword. This allows us to have generic properties which can be used all over the file or also accessed from another file. In this case I gave fixed values to make things go step by step. So if you try to display it, this will look like this:

Well, that’s a good start. Now, let’s play with that. Since the file is in the same folder it is automatically recognized within any other QML file from the same folder. Let’s put this in an application:
import QtQuick 1.0

Rectangle {
    id: tuto_root

    width: 360
    height: 360
    color: "darkgrey"

    Circle {
        id: tuto_first_circle
    }

    MouseArea {
        id: tuto_msa
        anchors.centerIn: parent
        onClicked: {
            Qt.quit();
        }
    }
}
This gives us :

Ok, I said, we can play with it… and I also said we can access these properties from the outside. Let’s do it. I want a smaller circle e.g. diameter = 100, with a blue color and at position (20,150). Here is the code; I think you can understand easily:
import QtQuick 1.0

Rectangle {
    id: tuto_root

    width: 360
    height: 360
    color: "darkgrey"

    Circle {
        id: tuto_first_circle
        selectedColor: "blue"
        posX: 20
        posY: 150
        size: 100
    }

    MouseArea {
        id: tuto_msa
        anchors.centerIn: parent
        onClicked: {
            Qt.quit();
        }
    }
}
Well, so far so good, I guess you understand how we can play with the properties

These properties are really useful. In the current case, this is more like creating a variable. These variables are assessed to some properties to make them change either easily (e.g. size is used for 3 properties) and/or from the outside (as we did when we integrated the circle in the main app). In this case, I set a default value for the properties. You don’t have to, but I recommend you to do it.

There is also another kind of property: the alias. An alias allows you to refer to the value of a field in a more generic way. The following code does exactly the same thing as before:
import QtQuick 1.0

Rectangle{
    id: circle_root

    property int posX: 0
    property int posY: 0
    property int size: 200
    property alias selectedColor: circle_root.color

    x: posX
    y: posY
    width: size
    height: size
    radius: size/2
}
Let’s say, right now, the difference might seem quite light, but when you will be playing more with QML you will see what suits the best for you. Anyway, we now have a reusable component. This is very interesting because QML provides components to create a bunch of components easily. For example, we can use a Repeater component within a Row component to generate a row of circle. Here is the code:
import QtQuick 1.0

Rectangle {
    id: tuto_root

    width: 360
    height: 360
    color: "darkgrey"

    Row {
        id: tuto_row
        Repeater {
            id: tuto_repeater
            model: 5
            Circle {
                id: tuto_first_circle
                selectedColor: "blue"
                size: 360 / tuto_repeater.model
            }
        }
    }

    MouseArea {
        id: tuto_msa
        anchors.centerIn: parent
        onClicked: {
            Qt.quit();
        }
    }
}
And the result:

As you can noticed, I reuse also the model property from the Repeater to adjust the size of the circle to the width of the window regarding the number I want. Quite easy, isn’t it?
That’s enough for today, I advise you to play with the properties, to play also with the Repeater component. For more details on this component, go here.

Have fun!

Thursday, January 20, 2011

Qt, improving day after day

Hey guys,

great news! Trolltech is working on merging both current Qt SDKs namely Qt SDK based on Qt 4.7 and Nokia Qt SDK. They are both including different features such as the deployment of application targeting Maemo or Symbian^3 for the Nokia Qt SDK, etc. Anyway, this is a great news!

Furthermore, the Qt Mobility framework has been finally included, which means: it is now possible to work with multimedia within QML. I really have to take a look at this one. ;)

You can read more about this here.

Enjoy!

EDIT:
Your attention please, I just installed the Qt SDK, full version. I imported the "First Tutorial" project but it didn't work. Here is the solution:

If you previously created your application with a version of QtCreator which generates a .qmlproject with
import QmlProject 1.1
You just need to downgrade this import to 1.0. Furthermore, since the version changes, the mainFile option is not available anymore. Please comment it out.

In your .qml files, do not worry about changing this:
import QtQuick 1.0
This still runs and do not impact the application (as far as I can tell). Only old QtCreator version do not support this import, if it's the case, change it to:
import Qt 4.7

Friday, January 7, 2011

Qt and Ruby, yes it's possible

Hey guys,

do you remember this article on Online File Synchronizer I shared awhile ago from one of my friends? Well, the same friend seems to be also interested in Qt. But unlike me, he knows Ruby.

That being said, he wrote an article (a short introduction actually) on how can people use QtRuby to develop easily nice applications. You can find the article here.

Enjoy. :)

Monday, January 3, 2011

First QML tutorial

Hello there people,

Here comes finally my first little introduction to QML. Well, I’ve been talking a lot about it… Finally you’ll understand why.

I have installed Qt 4.7.1 and QtCreator (which version, I don’t remember and anyway, it’s not very important for you). I just generated a normal QML project, and here is what I get:
import QtQuick 1.0

Rectangle {
    width: 360
    height: 360
    Text {
        anchors.centerIn: parent
        text: "Hello World"
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }
}
It is really important for you to understand this small code although it is actually self-explaining… I know, you are not stupid, but I’ll do it anyway. :)