My program needs to read/write a text (just a few lines) file with its settings to disk. To specify a path in code may work well on one platform, like windows, but if runs it on Linux, the path is not cross platform.
I am looking for a similar solution to QSettings
that saves settings to different paths or has its native ways to handle this. Programmers don't need to do with the details. But the text file is not suitable to be saved as a value in QSettings
.
No user interaction should be needed to obtain such path. The text file should persist across application restarts. It can't be a temporary file.
Is there an existing solution in Qt and what is the API that should be used?
The location of application-specific settings storage differs across platforms. Qt 5 provides a sensible solution via QStandardPaths
.
Generally, you'd store per-user settings in QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
. If you wish the settings not to persist in the user's roaming profile on Windows, you can use QStandardPaths::AppLocalDataLocation
, it has the meaning of AppDataLocation
on non-Windows platforms.
Before you can use the standard paths, you must set your application name via QCoreApplication::setApplicationName
, and your organization's name using setOrganizationName
or setOrganizationDomain
. The path will depend on these, so make sure they are unique for you. If you ever change them, you'll lose access to old settings, so make sure you stick with name and domain that makes sense for you.
The path is not guaranteed to exist. If it doesn't, you must create it yourself, e.g. using QDir::mkpath
.
int main(int argc, char ** argv) {
QApplication app{argc, argv};
app.setOrganizationDomain("stackoverflow.com");
app.setApplicationName("Q32525196.A32535544");
auto path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if (path.isEmpty()) qFatal("Cannot determine settings storage location");
QDir d{path};
if (d.mkpath(d.absolutePath()) && QDir::setCurrentPath(d.absolutePath())) {
qDebug() << "settings in" << QDir::currentPath();
QFile f{"settings.txt"};
if (f.open(QIODevice::WriteOnly | QIODevice::Truncate))
f.write("Hello, World");
}
}
If you want to save some user related data, you can get user home directory path using QDir::homePath()
.
There is QDir
to handle paths to dirs, QFileInfo
for platform independent file information and QDir
's homePath()
My proposal is to use these classes and use QDir::home()
or QDir::homePath()
to find a directory where to write to, since the user has write permissions in his homedir and it exists on each platform.
You can store file in application directory. Take a look at QCoreApplication::applicationDirPath()
.
From Qt documentation:
Returns the directory that contains the application executable.