Save (already-existing) QSetting into an INI file
Asked Answered
G

2

6

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.

Glynisglynn answered 19/1, 2012 at 17:51 Comment(0)
T
10

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 ) );
    }
}
Toni answered 19/1, 2012 at 18:6 Comment(0)
B
-1

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.

Banuelos answered 20/1, 2012 at 0:15 Comment(2)
Hi, thanks for taking time to answer. I agree with your 1st point. I do not agree with the 2nd, though: QSettings has a ctor accepting a file name as a parameter (where it will store its content). You can also use a combination of QCoreApplication::setApplicationName() and QCoreApplication::setOrganization*()` to precisely control the default path of QSettingsGlynisglynn
Sure enough... should always re-read the documentation before answering a question.Banuelos

© 2022 - 2024 — McMap. All rights reserved.