Skip to content

Commit

Permalink
extend qgsEnumKeyToValue to allow using the value (int) as a key (str…
Browse files Browse the repository at this point in the history
…ing)
  • Loading branch information
3nids committed Sep 10, 2020
1 parent 706ca2d commit 0b2abff
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/core/qgis.h
Expand Up @@ -513,18 +513,33 @@ template<class T> QString qgsEnumValueToKey( const T &value ) SIP_SKIP
/**
* Returns the value corresponding to the given \a key of an enum.
* If the key is invalid, it will return the \a defaultValue.
* If \a tryValueAsKey is true, it will try to use convert the string key to an enum value
* \since QGIS 3.6
*/
template<class T> T qgsEnumKeyToValue( const QString &key, const T &defaultValue ) SIP_SKIP
template<class T> T qgsEnumKeyToValue( const QString &key, const T &defaultValue, bool tryValueAsKey = true ) SIP_SKIP
{
QMetaEnum metaEnum = QMetaEnum::fromType<T>();
Q_ASSERT( metaEnum.isValid() );
bool ok = false;
T v = static_cast<T>( metaEnum.keyToValue( key.toUtf8().data(), &ok ) );
if ( ok )
{
return v;
}
else
return defaultValue;
{
// if conversion has failed, try with conversion from int value
if ( tryValueAsKey )
{
bool canConvert = false;
int intValue = key.toInt( &ok );
if ( canConvert && metaEnum.valueToKey( intValue ) )
{
return static_cast<T>( intValue );
}
}
}
return defaultValue;
}

/**
Expand Down

0 comments on commit 0b2abff

Please sign in to comment.