diff --git a/misc/desktoputils.cpp b/misc/desktoputils.cpp index dea7aeb..773fb99 100644 --- a/misc/desktoputils.cpp +++ b/misc/desktoputils.cpp @@ -69,4 +69,27 @@ std::optional isDarkModeEnabled() return std::nullopt; } +/*! + * \brief Invokes the specified callback when the color scheme changed. + * + * The first argument of the callback will be whether the color scheme is dark now (Qt::ColorScheme::Dark). + * The callback is invoked immediately by this function unless \a invokeImmediately is set to false. + * + * \remarks Whether dark mode is enabled can only be determined on Qt 6.5 or newer and only on certain + * platforms. If it cannot be determined the \a darkModeChangedCallback is never invoked. + */ +QMetaObject::Connection onDarkModeChanged(std::function &&darkModeChangedCallback, QObject *context, bool invokeImmediately) +{ +#if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)) + if (const auto *const styleHints = QGuiApplication::styleHints()) { + if (invokeImmediately) { + darkModeChangedCallback(styleHints->colorScheme() == Qt::ColorScheme::Dark); + } + return QObject::connect(styleHints, &QStyleHints::colorSchemeChanged, context, + [handler = std::move(darkModeChangedCallback)](Qt::ColorScheme colorScheme) { return handler(colorScheme == Qt::ColorScheme::Dark); }); + } +#endif + return QMetaObject::Connection(); +} + } // namespace QtUtilities diff --git a/misc/desktoputils.h b/misc/desktoputils.h index a67abc6..64b8728 100644 --- a/misc/desktoputils.h +++ b/misc/desktoputils.h @@ -3,10 +3,13 @@ #include "../global.h" +#include #include +#include #include +QT_FORWARD_DECLARE_CLASS(QObject) QT_FORWARD_DECLARE_CLASS(QString) namespace QtUtilities { @@ -14,6 +17,8 @@ namespace QtUtilities { QT_UTILITIES_EXPORT bool openLocalFileOrDir(const QString &path); QT_UTILITIES_EXPORT bool isPaletteDark(const QPalette &palette = QPalette()); QT_UTILITIES_EXPORT std::optional isDarkModeEnabled(); +QT_UTILITIES_EXPORT QMetaObject::Connection onDarkModeChanged( + std::function &&darkModeChangedCallback, QObject *context = nullptr, bool invokeImmediately = true); } // namespace QtUtilities