After searching around for a reason that qDebug() statements work fine with Qt\'s standard message handler but fail when I switch to my own, I\'m appealing here to see if an
As Frank Osterfeld mentioned in his comment:
On windows, qDebug() uses the debug channel, not stderr.
After delving into the QDebug code and QMessageLogger I've found my answer. The handy WinAPI function OutputDebugString
.
Usage (Modified from peppe's):
#include <QApplication>
#include <QtDebug>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
void MyMessageOutput(QtMsgType Type, const QMessageLogContext& Context, const QString &Message)
{
OutputDebugString(reinterpret_cast<const wchar_t *>(Message.utf16()));
}
int main(int argc, char **argv)
{
// A GUI application
QApplication app(argc, argv);
// Custom handler
qInstallMessageHandler(myMessageOutput);
qDebug() << "Printed in the console using my message handler in a windows GUI application";
// Default handler
qInstallMessageHandler(0);
qDebug() << "Also printed in the console!";
// Show GUI here
//MainForm *MF = new MainForm();
//MF->show();
return app.exec();
}
I can't reproduce your issue: this works correctly for me.
#include <QCoreApplication>
#include <QtDebug>
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
fprintf(stderr, "MESSAGE (%s:%u %s): %s\n", context.file, context.line, context.function, localMsg.constData());
fflush(stderr);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
qInstallMessageHandler(myMessageOutput);
qDebug() << "Printed in the console";
qInstallMessageHandler(0);
qDebug() << "Also printed in the console";
return app.exec();
}