Home > Net >  Load/Save settings using QSettings
Load/Save settings using QSettings

Time:12-21

I'm trying to Load / Save the text from all QLineEdit and QTextEdit from two windows, mainwindow and another called widget, this is how im saving/loading it:

void LoadSettings()
{
    QString m_sSettingsFile = 
         QApplication::applicationDirPath()   "/demosettings.ini";
    QSettings settings(m_sSettingsFile, QSettings::NativeFormat);

    for (auto btn : this->findChildren<QLineEdit*>())
    {
        QString text = settings.value("[M]"   btn->objectName(), "").toString();
        btn->setText(text);
    }

    for (auto btn : this->widget.findChildren<QTextEdit*>())
    {
        QString text = settings.value("[M]"   btn->objectName(), "").toString();
        btn->setText(text);        
    }

    for (auto btn : this->findChildren<QLineEdit*>())
    {
        QString text = settings.value("[W]"   btn->objectName(), "").toString();
        btn->setText(text);
    }

    for (auto btn : this->widget.findChildren<QTextEdit*>())
    {
        QString text = settings.value("[W]"   btn->objectName(), "").toString();
        btn->setText(text);        
    }
}



void SaveSettings()
{
    QString m_sSettingsFile = 
        QApplication::applicationDirPath()   "/demosettings.ini";
    QSettings settings(m_sSettingsFile, QSettings::NativeFormat);

    for (auto btn : this->findChildren<QLineEdit*>())
        settings.setValue("[M]"   btn->objectName(), btn->text());

    for (auto btn : this->findChildren<QTextEdit*>())
        settings.setValue("[M]"   btn->objectName(), btn->toPlainText());

    for (auto btn : this->widget.findChildren<QLineEdit*>())
        settings.setValue("[W]"   btn->objectName(), btn->text());

    for (auto btn : this->widget.findChildren<QTextEdit*>())
        settings.setValue("[W]"   btn->objectName(), btn->toPlainText());
}

But after calling Loading the text of all captured widgets became blank...

Also, there's a 'better' or most efficient way to write this task?

CodePudding user response:

Based on the tags that you used, I assume you're developing on MS Windows. NativeFormat of QSettings in MS Windows is Windows Registry. In your case, the file path that you pass as the first argument has to be a Windows Registry path, but you pass a FILE path. Either pass a windows registry path as first argument (i.e. HKEY_LOCAL_MACHINE\SOFTWARE\BLABLA), or use IniFormat as second argument.

CodePudding user response:

You got your prefixes mixed up in the LoadSettings. The second loop searches this->widget but loads settings from the "[M]" prefix. The third loop vice versa.

On a side note: QSettings supports grouping out of the box, no need for a custom prefix-based solution.

  • Related