Fix openLocalFileOrDir() on Windows

Not tested yet
This commit is contained in:
Martchus 2019-10-09 12:54:35 +02:00
parent e6a6d41df1
commit df03b97ced
2 changed files with 27 additions and 9 deletions

View File

@ -10,7 +10,7 @@ set(META_APP_DESCRIPTION
"Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models")
set(META_VERSION_MAJOR 6)
set(META_VERSION_MINOR 0)
set(META_VERSION_PATCH 1)
set(META_VERSION_PATCH 2)
set(META_APP_VERSION ${META_VERSION_MAJOR}.${META_VERSION_MINOR}.${META_VERSION_PATCH})
project(${META_PROJECT_NAME})
@ -179,6 +179,11 @@ set(CONFIGURATION_PACKAGE_SUFFIX
find_package(c++utilities${CONFIGURATION_PACKAGE_SUFFIX} 5.0.0 REQUIRED)
use_cpp_utilities()
# configure use of std::filesystem (so far only required on Windows)
if (WIN32)
use_standard_filesystem()
endif ()
# include modules to apply configuration
include(BasicConfig)
include(QtGuiConfig)

View File

@ -3,27 +3,40 @@
#include <QDesktopServices>
#include <QUrl>
#ifdef Q_OS_WIN32
#include <filesystem>
#endif
namespace QtUtilities {
/*!
* \brief Shows the specified file or directory using the default file browser.
* \remarks \a path musn't be specified as URL. (Conversion to URL is the
* purpose of this function).
* \remarks
* - The specified \a path must *not* be specified as URL. (The conversion to a URL suitable for
* QDesktopServices::openUrl() is the whole purpose of this function).
* - The Qt documentation suggests to use
* `QDesktopServices::openUrl(QUrl("file:///C:/Documents and Settings/All Users/Desktop", QUrl::TolerantMode));`
* under Windows. However, that does not work if the path contains a '#'. It is also better to use
* QUrl::DecodedMode to prevent QUrl from interpreting any of the paths characters in a special way.
*/
bool openLocalFileOrDir(const QString &path)
{
QUrl url(QStringLiteral("file://"));
#ifdef Q_OS_WIN32
// backslashes are commonly used under Windows
// -> replace backslashes with slashes to support Windows paths
// replace backslashes with regular slashes
QString tmp(path);
tmp.replace(QChar('\\'), QChar('/'));
QUrl url(QStringLiteral("file:///"));
// add a slash before the drive letter of an absolute path
if (std::filesystem::path(path.toStdString()).is_absolute()) {
tmp = QStringLiteral("/") + tmp;
}
url.setPath(tmp, QUrl::DecodedMode);
return QDesktopServices::openUrl(url);
#else
QUrl url(QStringLiteral("file://"));
url.setPath(path, QUrl::DecodedMode);
return QDesktopServices::openUrl(url);
#endif
return QDesktopServices::openUrl(url);
}
} // namespace QtUtilities