Skip to content

Instantly share code, notes, and snippets.

@paulmasri
Created January 20, 2025 10:53
Show Gist options
  • Save paulmasri/75dcd3386a4e8eaf705058240ef547d1 to your computer and use it in GitHub Desktop.
Save paulmasri/75dcd3386a4e8eaf705058240ef547d1 to your computer and use it in GitHub Desktop.
Get UWP app local data location
#include "AppDataLocation.h"
#ifdef NEEDS_UWP_APP_DATA_LOCATION
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Foundation.h>
#endif
QString appDataLocationPath()
{
static QString path; // calculate it only once and store it here
if (path.isEmpty())
{
#ifdef NEEDS_UWP_APP_DATA_LOCATION
try
{
auto localFolder = winrt::Windows::Storage::ApplicationData::Current().LocalFolder();
std::wstring folderPath = localFolder.Path().c_str();
path = QString::fromStdWString(folderPath);
}
catch (const std::exception& e)
{
qWarning() << "Failed to get the UWP AppData path:" << e.what() << "Falling back to QStandardPaths";
path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
}
#else
path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
#endif
}
return path;
}
# For use in Qt 6 Win32 apps, delivered via the Microsoft Store, where app data was previously saved by a Qt 5 UWP app.
# In this scenario, define `NEEDS_UWP_APP_DATA_LOCATION`.
QString appDataLocationPath();
# If using CMake, you'll need the following snippet. This assumes that the AppDataLocation files
# are in a subdirectory as a library called `AppDataLocationLib`.
# Put this code in the parent folder.
# When you set the CMake cache variable `NEEDS_UWP_APP_DATA_LOCATION` to `ON`, it adds the
# necessary configuration and defines NEEDS_UWP_APP_DATA_LOCATION for C++.
add_subdirectory(AppDataLocation)
option(NEEDS_UWP_APP_DATA_LOCATION "Use UWP app data location for backward compatibility" OFF)
if(NEEDS_UWP_APP_DATA_LOCATION)
message(STATUS "Applying legacy UWP app data location path, for delivery via the Microsoft Store")
target_compile_definitions(AppDataLocationLib PRIVATE WINVER=0x0A00 _WIN32_WINNT=0x0A00)
target_link_libraries(AppDataLocationLib PRIVATE WindowsApp)
target_compile_definitions(AppDataLocationLib PRIVATE NEEDS_UWP_APP_DATA_LOCATION)
endif()
target_link_libraries(${APP_TARGET}
PRIVATE
Qt6::Qml Qt6::Quick
AppDataLocationLib
...
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment