0
QString m_BoatProgramming("Boat Programming");
qDebug() << m_BoatProgramming;
qDebug() << QDate::currentDate();

Gives me:

"Boat Programming"
"Saturday 20th, 2016"

In some circumstances, rather than going through all the trouble of finding the terminal formatting codes, and manually putting in the metadata, I'd like it to output this:

QStringm_BoatProgramming:"Boat Programming"
QDate::currentDate():"Saturday 20th, 2016"

Is this already possible, or do I need to derive a class from qDebug() ?

4

1 回答 1

1

是的,可以使用消息处理程序。它还允许您将消息写入任何您需要的文件。

这是 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 将被执行两次。

于 2016-02-20T10:45:47.873 回答