How to print to console when using Qt

lesolorzanov picture lesolorzanov · Oct 7, 2010 · Viewed 285.4k times · Source

I'm using Qt4 and C++ for making some programs in computer graphics. I need to be able to print some variables in my console at run-time, not debugging, but cout doesn't seem to work even if I add the libraries. Is there a way to do this?

Answer

Goz picture Goz · Oct 7, 2010

If it is good enough to print to stderr, you can use the following streams originally intended for debugging:

#include<QDebug>

//qInfo is qt5.5+ only.
qInfo() << "C++ Style Info Message";
qInfo( "C Style Info Message" );

qDebug() << "C++ Style Debug Message";
qDebug( "C Style Debug Message" );

qWarning() << "C++ Style Warning Message";
qWarning( "C Style Warning Message" );

qCritical() << "C++ Style Critical Error Message";
qCritical( "C Style Critical Error Message" );

// qFatal does not have a C++ style method.
qFatal( "C Style Fatal Error Message" );

Though as pointed out in the comments, bear in mind qDebug messages are removed if QT_NO_DEBUG_OUTPUT is defined

If you need stdout you could try something like this (as Kyle Strand has pointed out):

QTextStream& qStdOut()
{
    static QTextStream ts( stdout );
    return ts;
}

You could then call as follows:

qStdOut() << "std out!";