_ZNote_转载_Qt_重定向qDebug到qt窗口部件方法

起源

看到 QtDev wiki 中有一篇文章QDebug 输出的浏览窗口。实现了将qDebug、qWarning等输出显示到一个窗口部件(QTextBrowser)中。

看完后,个人似乎对这堆代码不太感冒,于是自己试着写写,有了下面的代码:

实现了什么?

  • 定义了一个 MsgHandlerWapper 的类

  • qDebug、qWarning 等的输出会通过该类的 message 信号发送出来
  • 如果想让某个窗口接收消息,只需要定义一个槽,然后连接到该信号。

使用举例

如果要使用一个QPlainTextEdit作为log窗口,你只需要

  • 简单定义一个槽
  • connect到MsgHandlerWapper实例的信号即可

#include <QPlainTextEdit>
#include "msghandlerwapper.h"
class TextEdit:public QPlainTextEdit
{
    Q_OBJECT
public:
    explicit TextEdit(QWidget * parent = 0)
        :QPlainTextEdit(parent)
    {
        connect(MsgHandlerWapper::instance(),
                SIGNAL(message(QtMsgType,QString)),
                SLOT(outputMessage(QtMsgType,QString)));
    }
public slots:
    void outputMessage(QtMsgType type, const QString &msg)
    {
        appendPlainText(msg);
    }
};

代码

  • msghandlerwapper.h

/*
  (C) 2011 dbzhang800#gmail.com
*/
#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_Hs
  • msghandlerwapper.cpp

/*
  (C) 2011 dbzhang800#gmail.com
*/

#include "msgwapper.h"
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>

void static msgHandlerFunction(QtMsgType type, const char *msg)
{
    QMetaObject::invokeMethod(MsgHandlerWapper::instance(), "message"
                        , Q_ARG(QtMsgType, type)
                        , Q_ARG(QString, QString::fromLocal8Bit(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");
    qInstallMsgHandler(msgHandlerFunction);
}

参考


转载于:https://www.cnblogs.com/zpsoe/articles/7100392.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值