Qt Utilities 6.14.3
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
Loading...
Searching...
No Matches
desktoputils.cpp
Go to the documentation of this file.
1#include "./desktoputils.h"
2
3#include <QDesktopServices>
4#include <QUrl>
5#if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0))
6#include <QGuiApplication>
7#include <QStyleHints>
8#endif
9#ifdef Q_OS_WIN32
10#include <QFileInfo>
11#endif
12
13namespace QtUtilities {
14
25bool openLocalFileOrDir(const QString &path)
26{
27 QUrl url(QStringLiteral("file://"));
28
29#ifdef Q_OS_WIN32
30 // replace backslashes with regular slashes
31 QString tmp(path);
32 tmp.replace(QChar('\\'), QChar('/'));
33
34 // add a slash before the drive letter of an absolute path
35 if (QFileInfo(path).isAbsolute()) {
36 tmp = QStringLiteral("/") + tmp;
37 }
38 url.setPath(tmp, QUrl::DecodedMode);
39
40#else
41 url.setPath(path, QUrl::DecodedMode);
42#endif
43 return QDesktopServices::openUrl(url);
44}
45
49bool isPaletteDark(const QPalette &palette)
50{
51 return palette.color(QPalette::WindowText).lightness() > palette.color(QPalette::Window).lightness();
52}
53
59std::optional<bool> isDarkModeEnabled()
60{
61#if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0))
62 if (const auto *const styleHints = QGuiApplication::styleHints()) {
63 const auto colorScheme = styleHints->colorScheme();
64 if (colorScheme != Qt::ColorScheme::Unknown) {
65 return colorScheme == Qt::ColorScheme::Dark;
66 }
67 }
68#endif
69 return std::nullopt;
70}
71
81QMetaObject::Connection onDarkModeChanged(std::function<void(bool)> &&darkModeChangedCallback, QObject *context, bool invokeImmediately)
82{
83#if (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0))
84 if (const auto *const styleHints = QGuiApplication::styleHints()) {
85 if (invokeImmediately) {
86 darkModeChangedCallback(styleHints->colorScheme() == Qt::ColorScheme::Dark);
87 }
88 return QObject::connect(styleHints, &QStyleHints::colorSchemeChanged, context,
89 [handler = std::move(darkModeChangedCallback)](Qt::ColorScheme colorScheme) { return handler(colorScheme == Qt::ColorScheme::Dark); });
90 }
91#else
92 Q_UNUSED(darkModeChangedCallback)
93 Q_UNUSED(context)
94 Q_UNUSED(invokeImmediately)
95#endif
96 return QMetaObject::Connection();
97}
98
99} // namespace QtUtilities
QT_UTILITIES_EXPORT QMetaObject::Connection onDarkModeChanged(std::function< void(bool)> &&darkModeChangedCallback, QObject *context=nullptr, bool invokeImmediately=true)
Invokes the specified callback when the color scheme changed.
QT_UTILITIES_EXPORT std::optional< bool > isDarkModeEnabled()
Returns whether dark mode is enabled.
QT_UTILITIES_EXPORT bool isPaletteDark(const QPalette &palette=QPalette())
Returns whether palette is dark.
QT_UTILITIES_EXPORT bool openLocalFileOrDir(const QString &path)
Shows the specified file or directory using the default file browser.