Skip to content

Commit 1198dba

Browse files
committed
[settings] add method to get value for a setting associated to an enum
this will make sure the returned value is actually an existing entry of the enum
1 parent 52585cf commit 1198dba

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

python/core/qgssettings.sip.in

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010

1111

12+
1213
class QgsSettings : QObject
1314
{
1415
%Docstring
@@ -220,6 +221,7 @@ An optional Section argument can be used to get a value from a specific Section.
220221
sipIsErr = !sipRes;
221222
%End
222223

224+
223225
bool contains( const QString &key, const QgsSettings::Section section = QgsSettings::NoSection ) const;
224226
%Docstring
225227
Returns true if there exists a setting called key; returns false otherwise.

src/core/qgssettings.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
#define QGSSETTINGS_H
1919

2020
#include <QSettings>
21+
#include <QMetaEnum>
22+
2123
#include "qgis_core.h"
2224
#include "qgis.h"
2325

@@ -216,6 +218,30 @@ class CORE_EXPORT QgsSettings : public QObject
216218
% End
217219
#endif
218220

221+
#ifndef SIP_RUN
222+
223+
/**
224+
* Return the setting value for a setting defined on an enum.
225+
* This forces the output to be a valid and existing entry of the enum.
226+
* \note The enum needs to be declared with Q_ENUM
227+
*/
228+
template <class T>
229+
T enumSettingValue( const QString &key, const T &defaultValue,
230+
const Section section = NoSection ) const
231+
{
232+
T v = static_cast<T>( value( key, static_cast<int>( defaultValue ), section ).toInt() );
233+
QMetaEnum metaEnum = QMetaEnum::fromType<T>();
234+
if ( metaEnum.isValid() )
235+
{
236+
if ( !metaEnum.valueToKey( static_cast<int>( v ) ) )
237+
{
238+
v = defaultValue;
239+
}
240+
}
241+
return v;
242+
}
243+
#endif
244+
219245
/**
220246
* Returns true if there exists a setting called key; returns false otherwise.
221247
* If a group is set using beginGroup(), key is taken to be relative to that group.

0 commit comments

Comments
 (0)