重定向qDebug、qWarning等到某个Qt窗口部件
2011-07-09 22:55
337 查看
起源
看到 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_Hsmsghandlerwapper.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);
}
参考
http://developer.qt.nokia.com/wiki/Browser_for_QDebug_outputhttp://blog.csdn.net/dbzhang800/article/details/6449874
相关文章推荐
- 第一章-Qt入门 1.3 窗口部件的布局
- Qt-使用窗口部件
- 如何获得 Qt窗口部件在主窗口中的位置--确定鼠标是否在某一控件上与在控件上的位置
- Qt 在可视窗口部件上绘图
- QT内置的窗口部件类和对话框类
- qt窗口部件的布局
- 屏蔽Qt的qWarning() qDebug()语句输出
- Qt教程一 —— 第四章:使用窗口部件
- qt中在主窗口添加一个部件
- Qt——中心窗口部件
- 自定义QT窗口部件外观之QStyle
- QT中 窗口部件的 背景图片 的设置
- Qt入门(14)——父窗口部件和子窗口部件
- Qt窗口部件之行编辑器
- Qt 在可视窗口部件上绘图
- Qt:重定向QDebug输出到文件,并附上日期
- Qt入门(14)——父窗口部件和子窗口部件
- QT程序中引入designer自定义窗口部件
- QT窗口部件
- Qt5开发学习总结(三)——窗口部件的使用(QWidget和QDialog)