Save (already-existing) QSetting into an INI file

4k views Asked by At

I want to save an alredy-existing QSettings object into some INI file for backup.

The QSettings comes from the application's global settings, ie. it can be registry, ini file, etc.


In case it helps, my context is:

class Params
{
    // All params as data members
    // ...
    void loadGlobal ()
    {
        Qettings s; // Global parameters, paths set by application
        // Fill data members: s.value (...);
    }
};

class Algo
{
    Result run (Params p)
    {
        Result r = F(p);
        return r;
    }
};

int main (...)
{
    Params p;
    p.loadGlobal ();
    Algo a;
    Result r = a.run (p);

    // At this point, save Result and Params into a specific directory
    // Is there a way to do:
    p.saveToIni ("myparams.ini"); // <-- WRONG
}

A solution would be to add a saveTo (QSetting & s) method into the Params class:

class Params
{
    void saveTo (QSettings & s)
    {
        s.setValue (...);
    }
};

int main (...)
{
    Params p;
    p.loadGlobal ();
    QSettings bak ("myparams.ini", ...);
    p.saveTo (bak);
}

But I am looking for a solution without modifying the Params class.

2

There are 2 answers

0
Mike Buland On BEST ANSWER

Well, no, QT Doesn't really support this directly. I think your best bet is writing a helper class...something like:

void copySettings( QSettings &dst, QSettings &src )
{
    QStringList keys = src.allKeys();
    for( QStringList::iterator i = keys.begin(); i != keys.end(); i++ )
    {
        dst.setValue( *i, src.value( *i ) );
    }
}
2
Serge VK On

I think there are 2 issues:

  • QSettings does not have a copy constructor or assignment operator (that I know of), so you'll probably have to write your own copy using allKeys().
  • You can't save QSettings to an arbitrary file, but what you can do is set the path used for a specific format and scope using the static method QSettings::setPath(). Note that you need to do that before your backup QSettings object is created (and you would use format IniFormat).

If you're OK not having complete control over the resulting path, this should be sufficient. If not, you could still do the above, then get the file name using fileName() and use a system call to copy/move the file to the desired final location.