QErrorMessage: Forward log messages to original handler

The convenience of having a QErrorMessage pop up a dialog when a log
message is emitted should not prevent the existing message handler
(typically the default handler, logging to console e.g.) from getting
a stab at the messages.

Change-Id: I45ba9128f509e85cd60f4e678cf8ec50bb0f93f1
Reviewed-by: Richard Moe Gustavsen <richard.gustavsen@qt.io>
This commit is contained in:
Tor Arne Vestbø 2022-11-18 16:55:28 +01:00
parent 21127b587b
commit 45e33954ef

View File

@ -149,8 +149,15 @@ static QString msgType2i18nString(QtMsgType t)
return QCoreApplication::translate("QErrorMessage", messages[t]); return QCoreApplication::translate("QErrorMessage", messages[t]);
} }
static QtMessageHandler originalMessageHandler = nullptr;
static void jump(QtMsgType t, const QMessageLogContext &context, const QString &m) static void jump(QtMsgType t, const QMessageLogContext &context, const QString &m)
{ {
const auto forwardToOriginalHandler = qScopeGuard([&] {
if (originalMessageHandler)
originalMessageHandler(t, context, m);
});
if (!qtMessageHandler) if (!qtMessageHandler)
return; return;
@ -224,10 +231,12 @@ QErrorMessage::~QErrorMessage()
{ {
if (this == qtMessageHandler) { if (this == qtMessageHandler) {
qtMessageHandler = nullptr; qtMessageHandler = nullptr;
QtMessageHandler tmp = qInstallMessageHandler(nullptr); QtMessageHandler currentMessagHandler = qInstallMessageHandler(nullptr);
// in case someone else has later stuck in another... if (currentMessagHandler != jump)
if (tmp != jump) qInstallMessageHandler(currentMessagHandler);
qInstallMessageHandler(tmp); else
qInstallMessageHandler(originalMessageHandler);
originalMessageHandler = nullptr;
} }
} }
@ -261,6 +270,10 @@ void QErrorMessage::done(int a)
isn't one already. isn't one already.
The object will only output log messages of QLoggingCategory::defaultCategory(). The object will only output log messages of QLoggingCategory::defaultCategory().
The object will forward all messages to the original message handler.
\sa qInstallMessageHandler
*/ */
QErrorMessage * QErrorMessage::qtHandler() QErrorMessage * QErrorMessage::qtHandler()
@ -269,7 +282,7 @@ QErrorMessage * QErrorMessage::qtHandler()
qtMessageHandler = new QErrorMessage(nullptr); qtMessageHandler = new QErrorMessage(nullptr);
qAddPostRoutine(deleteStaticcQErrorMessage); // clean up qAddPostRoutine(deleteStaticcQErrorMessage); // clean up
qtMessageHandler->setWindowTitle(QCoreApplication::applicationName()); qtMessageHandler->setWindowTitle(QCoreApplication::applicationName());
qInstallMessageHandler(jump); originalMessageHandler = qInstallMessageHandler(jump);
} }
return qtMessageHandler; return qtMessageHandler;
} }