QT,将 qDebug() 与自定义消息处理程序一起使用不显示 line/file/function 信息

QT, using qDebug() with custom message handler does not show line/file/function info

我从 https://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler 中获取了以下代码 我想访问 myMessageOutput()

中的 context.file、context.line、context.function
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    const char *file = context.file ? context.file : "";
    const char *function = context.function ? context.function : "";
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    }
}

int main(int argc, char **argv)
{
    qInstallMessageHandler(myMessageOutput);
    QApplication app(argc, argv);
    ...
    return app.exec();
}

在调试构建中(使用 `qDebug() << "test logging")显示有关上下文的详细信息。line/file/number。 在发布版本中,信息为 nullptr 或 0(行)。 转载于 Windows (QT 5.12)

我已经在 Qt 5.15.2 中用 gcc(在 Linux 中)测试了你的代码,它在调试和发布模式下都有效,我无法重现你的问题。然而,在文档页面 QMessageLogContext Class 中提到:

Note: By default, this information is recorded only in debug builds. You can overwrite this explicitly by defining QT_MESSAGELOGCONTEXT or QT_NO_MESSAGELOGCONTEXT.

因此,在您的 project.pro 文件中添加以下行可能会解决您的问题:

DEFINES+= QT_MESSAGELOGCONTEXT

不要忘记 运行 qmake 并重建您的项目以查看效果。