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);
}
评论区