7

I have seen bits of Qt code that uses qDebug as if it were printf()

qDebug( format, ... );

Mostly i see it used like std::cout

qDebug() << "one " << var_one;

What is the difference in the usages and when is it correct/better to use one of the other? The Qt help online somehow seems to reference the function version but never explain it.

1 Answer 1

7

qDebug(pattern, object1, object2) it's basically the old fashioned fprintf(stderr, pattern, object1, object2), as such you depend on compiler support to avoid - for instance - to crash your program with wrong patterns, like int x; qDebug("%s\n", x);. Well, GCC catches this one, but the compiler cannot always know if the pattern is appropriate, I think.

I always use qDebug() << object << ...;, as the documentation states

If you include QtDebug, a more convenient syntax is also available:

qDebug() << "Brush:" << myQBrush << "Other value:" << i;

With this syntax, the function returns a QDebug object that is configured to use the QtDebugMsg message type. It automatically puts a single space between each item, and outputs a newline at the end. It supports many C++ and Qt types.

you can pass most of Qt objects to qDebug() << ... and get them rendered in readable way

try for instance qDebug() << QTime::currentTime();

5
  • I'm using qDebug in next way (if I need complex formatting): qDebug() << QString( "%1 - %2" ).arg( "something1").arg( 42 ); Apr 3, 2014 at 9:16
  • it's more complex than needed: better qDebug() << "something" << " - " << 42;`
    – CapelliC
    Apr 3, 2014 at 9:18
  • 1
    it's not complex. If you need to out a lot of string, combined with arguments - you will write a lot of code. Compare, what is more readable: qDebug() << QString("Coordinates: \"%1 x %2 x %3\"").arg(x[i]).arg(y[i]).arg(z[i]); or qDebug() << "Coordinates: \"" << x[i] << " x " << y[i] << " x " << z[i]; << "\"" Apr 3, 2014 at 11:55
  • IMHO, the whole << version of stream output is clumsy. printf() is far more easly formatted. Imagine the mix of width() and fill() tokens that would go in the previous example if it were being formatted into a table or form.
    – Wes Miller
    Apr 4, 2014 at 19:12
  • I found this information about qDebug() as a function.
    – Wes Miller
    Apr 4, 2014 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.