Qt - How to save a configuration file on multiple platforms

I am writing a Qt application that needs to save some settings in the user configuration directory.

I found the following code to get this folder:

#ifdef Q_WS_WIN
    path = QDir::homePath() + "/Application Data/Timely";
#else
    path = QDir::homePath() + "/.config/Timely";
#endif

This fails in Windows 7 because Windows 7 uses application data / roaming / [YourApp]. How can I get the user configuration folder in a cross-platform way? Am I missing something obvious? (this should be an easy task)

+3
source share
4 answers

Depends on the settings you want to record, but I would suggest using QSettings .

+11
source
+6

, QSettings, Qt ( ).

//:

void MainWindow::readSettings()
{
    QSettings settings("Moose Soft", "Clipper");

    settings.beginGroup("MainWindow");
    resize(settings.value("size", QSize(400, 400)).toSize()); // note the 400x400 defaults if there is no saved settings yet
    move(settings.value("pos", QPoint(200, 200)).toPoint()); // here default pos is at 200,200
    settings.endGroup();
}

void MainWindow::writeSettings()
{
    QSettings settings("Moose Soft", "Clipper");

    settings.beginGroup("MainWindow");
    settings.setValue("size", size());
    settings.setValue("pos", pos());
    settings.endGroup();
}

readSettings() MainWindow:

MainWindow::MainWindow()
{
    ...
    readSettings();
}

while writeSettings() :

void MainWindow::closeEvent(QCloseEvent *event)
{
        writeSettings();
        event->accept();
}

, : , . , , Windows, QSettings::NativeFormat , %appdata%, QSettings::IniFormat. , .

My personal preference is to install IniFormatfor Windows (since registry data is not easily portable) and NativeFormatfor Linux and macOS, for example:

QSettings *settings;

if ( (os == "Linux") | (os == "macOS") ) {
    settings = new QSettings(QSettings::NativeFormat, QSettings::UserScope, "Moose Soft", "Clipper");
} else {
    settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "Moose Soft", "Clipper");
};
0
source

Source: https://habr.com/ru/post/1778805/


All Articles