Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a settings storage path in a cross-platform way in Qt?

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?

like image 831
canoe Avatar asked Sep 11 '15 13:09

canoe


1 Answers

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");   
  }
}
like image 119
Kuba hasn't forgotten Monica Avatar answered Nov 10 '22 18:11

Kuba hasn't forgotten Monica