Qt - How to save a configuration file on multiple platforms

前端 未结 4 993
一生所求
一生所求 2021-01-20 15:35

I\'m writing a Qt application that needs to save some settings to the user\'s configuration directory.

I\'ve come up with the following code to get this folder:

4条回答
  •  甜味超标
    2021-01-20 16:27

    In addition to provided answers suggesting to use QSettings, I will shamelessly copy here Qt's own example from documentation (I slightly edited it, though).

    Here are the functions to read and write settings from the file/registry/whatever:

    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();
    }
    

    The readSettings() function may be called from the MainWindow constructor:

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

    while writeSettings() from the close event handler:

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

    Last but not least, take a note, that settings format may be different. For example, if you want settings to be saved in the registry in Windows, you should pass QSettings::NativeFormat to the constructor, but if you'd like text config in the %appdata%, pass QSettings::IniFormat instead. In the example above format isn't passed, so it's native by default.

    My personal preference to set IniFormat for Windows (because registry data isn't easily transferable) and NativeFormat for Linux and macOS, like this:

    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");
    };
    

提交回复
热议问题