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?
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!";
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With