一、界面中添加一个QTextBrowser
二、相关源码
.hpp
#ifndef LOGLOOKWIDGET_H
#define LOGLOOKWIDGET_H#include <QWidget>
#include <QMutex>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QTime>
#include <QFontDialog>namespace Ui {
class LogLookWidget;
}class LogLookWidget : public QWidget
{Q_OBJECT
signals:void messageOutputSignal(QtMsgType type, int line, QString file, const QString &msg);
public:explicit LogLookWidget(QWidget *parent = nullptr);~LogLookWidget();
private:void controlInit();static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
private slots:void messageOutputSlot(QtMsgType type, int line, QString file, const QString &msg);
private:Ui::LogLookWidget *ui;static LogLookWidget *instance;QFile *logFile = nullptr;QTextStream *logStream = nullptr;
};#endif // LOGLOOKWIDGET_H
.cpp
#include "logLookWidget.h"
#include "ui_logLookWidget.h"LogLookWidget *LogLookWidget::instance = nullptr;LogLookWidget::LogLookWidget(QWidget *parent) :QWidget(parent),ui(new Ui::LogLookWidget)
{ui->setupUi(this);instance = this;this->controlInit();
}LogLookWidget::~LogLookWidget()
{qInstallMessageHandler(nullptr);delete ui;
}void LogLookWidget::controlInit()
{this->setWindowTitle(tr("日志查看"));qInstallMessageHandler(LogLookWidget::messageOutput)connect(instance,&LogLookWidget::messageOutputSignal,this,&LogLookWidget::messageOutputSlot);
}void LogLookWidget::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{emit instance->messageOutputSignal(type,context.line,context.file,msg);
}void LogLookWidget::messageOutputSlot(QtMsgType type, int line, QString file, const QString &msg)
{static QMutex mutex;mutex.lock();QString tag;QString time;QString fileAndLine;switch(type){case QtDebugMsg:tag = QString("%1").arg("D/",-5);break;case QtInfoMsg:tag = QString("%1").arg("I/",-5);break;case QtWarningMsg:tag = QString("%1").arg("W/",-5);break;case QtCriticalMsg:tag = QString("%1").arg("E/",-5);break;case QtFatalMsg:tag = QString("%1").arg("F/",-5);break;}time = QString("%1").arg("["+QTime::currentTime().toString("hh:mm:ss.zzz")+"]",-15);fileAndLine = QString("%1").arg("("+file.split("\\").last()+":"+QString::number(line)+")",-35,' ');QString logMsg;logMsg.append(tag);logMsg.append(" ");logMsg.append(time);logMsg.append(" ");logMsg.append(fileAndLine);logMsg.append(" ");logMsg.append(msg);// std::cout<<logMsg.toStdString();//将信息显示到界面上this->ui->textBrowser->append(logMsg);logMsg.append("\n");//将信息保存到文件中if(this->logStream)*this->logStream<<logMsg;mutex.unlock();
}
注意:
1、函数messageOutput
只能是静态成员函数或外部函数。
2、static LogLookWidget *instance的作用是通过信号与槽的方法将信息转到类内成员函数,从而完成将信息显示到界面。
3、qInstallMessageHandler(LogLookWidget::messageOutput)的作用是将信息输出载体转化到messageOutput这个函数上,对应的qInstallMessageHandler(nullptr);是取消。