是的,可以使用消息处理程序。它还允许您将消息写入任何您需要的文件。
这是 doc 中的修改示例以符合您的要求:
#include <QApplication>
#include <stdio.h>
#include <stdlib.h>
#include <typeinfo>
#include <QDebug>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
}
}
#define MY_DEBUG( exp ) qDebug() << typeid(exp).name() << #exp << exp
int main(int argc, char **argv)
{
qInstallMessageHandler(myMessageOutput);
QApplication app(argc, argv);
QString str = "Shit happens!";
MY_DEBUG( str );
return 0;
}
将输出:
Debug: class QString str "Shit happens!" (..\ProjectorControl\ProjectorControl\main.cpp:56, int __cdecl main(int,char **))
我认为使用更多的宏魔法或模板可以实现更方便的行为。
注意:使用这个宏要小心:实际上 exp 将被执行两次。