Using qDebug

GUI debuggers are the norm these days, however, I still feel the urge to do a little printf-debugging now and then. It might be wrong, it might be silly but it works.

I like to develop the odd graphical application and I like use Qt. For Qt, the nice Norwegian Trolls have provided the qDebug function. You can use it right away just like your old trusted printf:

if(complexStatement(x))
{
    qDebug("This code executes when x = %d", x);
    ...

This works great for integers and other basic types. But, take the fairly common class QColor. Your first thought would probably be to write out each component manually:

qDebug("Color is: %x, %x, %x",
       color.red(),
       color.green(),
       color.blue());

This can be rather tedious, and there are types which are complex to print. For instance, QString, stores unicode strings and uses implicit sharing to reduce copying overhead. This gives you quick internationalized applications, but you cannot easily print the thing. To the rescue: qPrintable.

qDebug("A string: %s", qPrintable(myString));

The qPrintable macro is handy, but you also need to be aware of its quirks. The returned const char pointer is only valid for that very call. I.e. you cannot store it and re-use it - that will most likely give you garbage output.

// Do not do this
const char *text = qPrintable(myString);
// ...
doSomething(text);

For those who refer to printf debugging as cout debugging, and those who like to have a more convenient API, I recommend including the QtDebug header. This way, you can stream most of Qt's types to qDebug. This means a more convenient API for when you need to print QColor values, etc:

qDebug() << color;

Printing using qDebug usually results in console output (you might have to add CONFIG += console to your project file to get output at all on some platforms). However, you can also install a message handler to present your messages in a GUI window, translate them, paint them in colors or just put them in a log file.

Load Disqus comments