Search code examples
c++qtpathdirectoryprojects-and-solutions

How to get project name from C++ code?


I want to write to <CacheDir>/myProjectName where <CacheDir> is the value of:

QStandardPaths::writableLocation(QStandardPaths::CacheLocation)

But I don't want to hardcode my project name in C++ because that would create 2 places to update. Is there any way to get it programatically?


Solution

  • The standard Qt way that application names are handled is with QCoreApplication::applicationName() - of course you have to set that somewhere (usually in your main() function where you create the application).

    Once you have done that, the application name is actually used as part of the application specific QStandardPath - e.g. the documentation for CacheLocation says that for windows, the CacheLocation is C:/Users/<USER>/AppData/Local/<APPNAME>/cache, meaning that the application name is already in the path.

    So for your example you could create a unique path for your app like this:

    auto myCacheFile = QString("%1/cache.txt")
                 .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));