Created
December 18, 2022 12:24
-
-
Save garywill/f6b75e9904d02e6f931b589c3937b5e2 to your computer and use it in GitHub Desktop.
Qt5 log to both stdout/stderr and textEdit with qInfo qDebug etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "mainwindow.h" | |
#include <QApplication> | |
#include <QDateTime> | |
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg); | |
int main(int argc, char *argv[]) | |
{ | |
QApplication a(argc, argv); | |
qInstallMessageHandler(myMessageOutput); | |
MainWindow w; | |
w.show(); | |
return a.exec(); | |
} | |
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) | |
{ | |
QByteArray localMsg = msg.toLocal8Bit(); | |
const char *file = context.file ? context.file : "未知文件"; | |
const char *function = context.function ? context.function : "未知函数"; | |
const char * timeStr = qUtf8Printable(QDateTime::currentDateTime().toString("HH:mm:ss")); | |
QString qstr ; | |
switch (type) { | |
case QtDebugMsg: | |
fflush(stderr); | |
qstr = QString("DBG: %1\t( %2 来自文件 %3 的第 %4 行, 函数 %5 )") | |
.arg( localMsg.constData() ) | |
.arg( timeStr) | |
.arg( file) | |
.arg( context.line) | |
.arg( function ) ; | |
fprintf(stdout, qUtf8Printable(qstr+'\n') ); | |
fflush(stdout); | |
break; | |
case QtInfoMsg: | |
fflush(stderr); | |
qstr = QString(localMsg.constData()); | |
fprintf(stdout, qUtf8Printable(qstr+'\n') ); | |
fflush(stdout); | |
break; | |
case QtWarningMsg: | |
fflush(stdout); | |
qstr = QString(localMsg.constData()); | |
fprintf(stderr, qUtf8Printable(qstr+'\n') ); | |
fflush(stderr); | |
break; | |
case QtCriticalMsg: | |
fflush(stdout); | |
qstr = QString("CRITICAL: %1 (%2:%3, %4)") | |
.arg( localMsg.constData() ) | |
.arg( file) | |
.arg( context.line) | |
.arg( function ) ; | |
fprintf(stderr, qUtf8Printable(qstr+'\n') ); | |
fflush(stderr); | |
break; | |
case QtFatalMsg: | |
fflush(stdout); | |
qstr = QString("FATAL: %1 (%2:%3, %4)") | |
.arg( localMsg.constData() ) | |
.arg( file) | |
.arg( context.line) | |
.arg( function ) ; | |
fprintf(stderr, qUtf8Printable(qstr+'\n') ); | |
fflush(stderr); | |
break; | |
} | |
MainWindow::teLog->append(qstr); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment