Last active
August 29, 2015 14:06
-
-
Save enkore/fc145d14d01e247d0f12 to your computer and use it in GitHub Desktop.
Qt utility macro for creating a proper QSettings hierarchy without hassle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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