Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Qt: Can I output to `stdout`, as easy as I can output to `stderr` using qDebug()?

Up until now, I output everything using qDebug().noquote(). This is easy because it just requires a simple #import <QDebug>

Now I need everything to output to stdout, but I don't know how to do it easily. This how I was taught:

QTextStream cout(stdout, QIODevice::WriteOnly);

However, creating a new object is a tad bit more cumbersome than a simple #import <QDebug>. What is the good/least cumbersome way to handle stdout in qt?

like image 579
Anon Avatar asked Feb 05 '23 20:02

Anon


2 Answers

qDebug(), qInfo(), etc. are all piped to a default message handler. But you can easily install your own that writes the debug strings to a different stream, file, or anything. All you need to do is define a message handler function and install it using qInstallMessageHandler().

Putting it all together, here's a complete example:

#include <QDebug>

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QTextStream cout(stdout, QIODevice::WriteOnly);
    cout << msg << endl;
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(myMessageOutput);

    qDebug().noquote() << "Hello world!";
}
like image 119
MrEricSir Avatar answered Feb 07 '23 10:02

MrEricSir


The best way is the one you mentioned. You don't have to create a new local variable:

QTextStream(stdout) << "Hello world!" << endl;

If the source text is not Latin-1 encoded then you need to convert to QString before passing it to the stream operator:

QTextStream(stdout) << QString::fromUtf8("utf8 literal") << endl;
like image 27
Jason Haslam Avatar answered Feb 07 '23 09:02

Jason Haslam