Skip to content

Instantly share code, notes, and snippets.

@enkore
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enkore/fc145d14d01e247d0f12 to your computer and use it in GitHub Desktop.
Save enkore/fc145d14d01e247d0f12 to your computer and use it in GitHub Desktop.
Qt utility macro for creating a proper QSettings hierarchy without hassle
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QSettings>
#include <QMap>
#include <QObject>
#include <QStringList>
extern QMap<QObject*, QSettings*> _settings_h_settings;
// rev. 2: Use QStringList instead of repeated QString formatting
/**
* @brief returns a QSettings with a reasonable prefix set
* @note only works inside methods of QObject-derived classes
* @note first use should be early and unconditional, e.g. in the constructor
* @note add definition of _settings_h_settings to one compilation unit
*/
#define settings \
(*[this]() -> QSettings* { \
if(_settings_h_settings.contains(this)) { \
return _settings_h_settings[this]; \
} \
QStringList path{this->objectName()}; \
QObject *p{this->parent()}; \
while(p) { \
if(p->objectName().size()) { \
path.prepend(p->objectName()); \
} \
p = p->parent(); \
} \
QSettings *s{new QSettings(this)}; \
s->beginGroup(path.join("/")); \
_settings_h_settings[this] = s; \
return s; \
}())
#endif // SETTINGS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment