起源

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

实现了什么?

  • 定义了一个 MsgHandlerWapper 的类

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

使用举例

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

#include <QPlainTextEdit>
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);
    }
};
代码

/*
  (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

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

#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>

void static msgHandlerFunction(QtMsgType type, const char *msg)
{
                        , 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)
{
    qInstallMsgHandler(msgHandlerFunction);
}
参考

相关文章: