侧边栏壁纸
博主头像
三味的小站博主等级

世界上没有偶然,有的只是必然的结果。

  • 累计撰写 61 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
Qt

Qt Debug重定向到文本控件

三味线
2019-06-24 / 0 评论 / 0 点赞 / 10 阅读 / 1971 字

Qt中可以将qDebug()输出的信息重定向通过窗口控件输出;

定义一个MsgHandlerWapper类用于转接消息:

// msghandlerwapper.h
#ifndef MSGHANDLERWAPPER_H
#define MSGHANDLERWAPPER_H
#include <QtCore/QObject>
class MsgHandlerWapper:public QObject
{
    Q_OBJECT
public:
    static MsgHandlerWapper * instance();
signals:
    void message(QtMsgType type, const QString &msg);
private:
    MsgHandlerWapper();
    static MsgHandlerWapper * m_instance;
};
#endif // MSGHANDLERWAPPER
// msghandlerwapper.cpp
#include "msghandlerwapper.h"
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>
#include <QtMessageHandler>
void static msgHandlerFunction(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    Q_UNUSED(context)
    QMetaObject::invokeMethod(MsgHandlerWapper::instance(), "message"
                        , Q_ARG(QtMsgType, type)
                        , Q_ARG(QString, msg));
}
MsgHandlerWapper * MsgHandlerWapper::m_instance = 0;
MsgHandlerWapper * MsgHandlerWapper::instance()
{
    static QMutex mutex;
    if (!m_instance) {
        QMutexLocker locker(&mutex);
        if (!m_instance)
            m_instance = new MsgHandlerWapper;
    }
    return m_instance;
}
MsgHandlerWapper::MsgHandlerWapper()
    :QObject(qApp)
{
    qRegisterMetaType<QtMsgType>("QtMsgType");
    qInstallMessageHandler(msgHandlerFunction);
}

在自己的窗口类中定义一个槽响应message信号:

connect(MsgHandlerWapper::instance(),
                SIGNAL(message(QtMsgType,QString)),
                SLOT(outputDebugMsg(QtMsgType,QString)));
void MyWidget::outputDebugMsg(QtMsgType type, const QString &msg)
{
    Q_UNUSED(type)
    mLogBrowser->append(msg);
}

0

评论区