Search code examples
c++qtqsettings

Is it possible to Serialize QSettings and then recover them?


I would like to pass the settings saved with QSetting through two instances of an application, for example through a socket.

I could not see any function in the official documentation. The only thing I read is for example this post

Save Configuration Settings to XML file in QT?

But I do not want to save the settings in a XML file, for example in Windows I want to continue using the Registry.

I just want to collect all the settings, and pass them through a socket. And the receiver could check the settings and eventually substitute its own settings with the received ones.

Well, I suppose I could do something similar using QSettings::allKeys(), checking all the values, convert to strings, etc etc...but do you know if there is some native function in Qt already implemented?

Thanks to everyone in advance


Solution

  • Best solution that I found:

    Create a QMap from QSettings

    QMap<QString, QVariant> keysValuesPairs;
    QStringList keys = settings.allKeys();
    QStringListIterator it(keys);
    while ( it.hasNext() )
    {
        QString currentKey = it.next();
        keysValuesPairs.insert(currentKey, settings.value(currentKey));
    }
    

    And then write it in a QJson with the function (see the official documentation http://doc.qt.io/qt-5/qjsonobject.html)

    QJsonObject::fromVariantMap

    then in the other side recover it with

    QJsonObject::toVariantMap()

    and rewrite the settings

    for ( int i = 0; i < keys.size(); i++ )
    {
        settings.setValue( keys.at(i), keysValuesPairsMap.value(keys.at(i)) );
    }