开发笔记

  • 首页
  • 工具箱
三味线的博客
  1. 首页
  2. Qt
  3. 正文

Qt Debug重定向到文本控件

2019-06-24 1182点热度 3人点赞 0条评论

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);
}
标签: Qt
最后更新:2020-06-06

三味线

不吃咸鱼的喵

点赞
< 上一篇
下一篇 >

文章评论

取消回复

Captcha Code

COPYRIGHT © 2022 voidcat.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备18010095号-1