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

前端 未结 2 1472
傲寒
傲寒 2020-12-09 11:24

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

相关标签:
2条回答
  • 2020-12-09 11:46

    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();
    }
    
    0 讨论(0)
  • 2020-12-09 11:50

    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();
    }
    
    0 讨论(0)
提交回复
热议问题