使用qInstallMsgHandler将日志保存到文件 1 在main函数之前定义回调函数 void myMessageOutput(QtMsgType type, const char *msg) { QString text; switch (type) { case QtDebugMsg: text = QString("Debug: %1").arg(msg); break; case QtWarningMsg: text = QString("Warning: %1").arg(msg); break; case QtCriticalMsg: text = QString("Critical: %1").arg(msg); break; case QtFatalMsg: text = QString("Fatal: %1").arg(msg); abort(); } QFile file("111.txt"); file.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream ts(&file); ts<<text<<endl; } 2 在main函数中注册myMessageOutput qInstallMsgHandler(myMessageOutput); 3 注册后,在该程序的任何地方使用即可。 qDebug("This is a debug message"); qWarning("This is a warning message"); qCritical("This is a critical message"); qFatal("This is a fatal message");