How does Qt5 redirect qDebug() statements to the Qt Creator 2.6 console

旧巷老猫 提交于 2019-11-28 07:39:29

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!