How to load default settings with KConfig on kdeli

2020-08-01 08:32发布

问题:

I've a question about KConfig usage. I'm able to write and read settings in my .kde4/share/config/_appname_rc configuration file like that

 KConfig basicconf;
 KConfigGroup conf = KConfigGroup(basicconf.group("Settings"));
 conf.writeEntry("filepath",QString("/path/"));
 basicconf.sync();

But I don't understand how to use a "default" configuration file to read at first time i run my application, or in case if application settings needs reset.

I prefer do not use KConfig XT because my project is tiny and KConfigXT with kcfgc* files seems excessive.

Thank you in advance

回答1:

First, this:

KConfigGroup conf = KConfigGroup(basicconf.group("Settings"));

can be written more clearly, at least imho, as:

KConfigGroup conf(&basicconf, "Settings");

Also note that "General" is the most common "generic" group name used. Anyways...

You can install a default config file with your application; install it to $PREFIX/share/config/, which is easily achieved with this in your CMakeLists.txt file:

install(FILES <your config file> DESTINATION ${CONFIG_INSTALL_DIR})

KConfig handles all the magic of merging from there; you don't have to do a thing.

As for KConfigXT being overkill, there are many benefits to using it, including automating your config dialogs, ensuring bounds and legal values are enforced, etc. Writing a small file, popping an entry in the CMakeLists.txt file is usually much less work than doing what it gives you for free by hand. There's a great tutorial on TechBase on this.



回答2:

Use KGlobal::config() to get a pointer to the default KConfig object owned by your app. It automagically refers to the file in $KDEHOME/share/config.

KConfig XT can make sense because

  • the API of the generated YourSettings object is specific to your application; it's a bit easier to understand the meaning of YourSettings::setFilePath(path) than conf.writeEntry("filepath", path);
  • Your app may grow; it's easier to start with KConfig XT than rip and replace it later.
  • Defaults are specified in the via the .kcfg XML rather than hardcoded in a few places of your app, and you have a setDefault() method to reset all values.