Add method to retrieve variables from a QgsExpressionContext as a QVariantMap

This commit is contained in:
Nyall Dawson 2017-01-09 13:38:47 +10:00
parent a7806d1a39
commit d25fcec03d
4 changed files with 57 additions and 0 deletions

View File

@ -247,6 +247,13 @@ class QgsExpressionContext
*/
QVariant variable( const QString& name ) const;
/**
* Returns a map of variable name to value representing all the expression variables
* contained by the context.
* @note added in QGIS 3.0
*/
QVariantMap variablesToMap() const;
/** Returns true if the specified variable name is intended to be highlighted to the
* user. This is used by the expression builder to more prominently display the
* variable.

View File

@ -274,6 +274,17 @@ QVariant QgsExpressionContext::variable( const QString& name ) const
return scope ? scope->variable( name ) : QVariant();
}
QVariantMap QgsExpressionContext::variablesToMap() const
{
QStringList names = variableNames();
QVariantMap m;
Q_FOREACH ( const QString& name, names )
{
m.insert( name, variable( name ) );
}
return m;
}
bool QgsExpressionContext::isHighlightedVariable( const QString &name ) const
{
return mHighlightedVariables.contains( name );

View File

@ -303,6 +303,13 @@ class CORE_EXPORT QgsExpressionContext
*/
QVariant variable( const QString& name ) const;
/**
* Returns a map of variable name to value representing all the expression variables
* contained by the context.
* @note added in QGIS 3.0
*/
QVariantMap variablesToMap() const;
/** Returns true if the specified variable name is intended to be highlighted to the
* user. This is used by the expression builder to more prominently display the
* variable.

View File

@ -51,6 +51,8 @@ class TestQgsExpressionContext : public QObject
void cache();
void valuesAsMap();
private:
class GetTestValueFunction : public QgsScopedExpressionFunction
@ -688,5 +690,35 @@ void TestQgsExpressionContext::cache()
QVERIFY( !c.cachedValue( "test" ).isValid() );
}
void TestQgsExpressionContext::valuesAsMap()
{
QgsExpressionContext context;
//test retrieving from empty context
QVERIFY( context.variablesToMap().isEmpty() );
//add a scope to the context
QgsExpressionContextScope* s1 = new QgsExpressionContextScope();
s1->setVariable( "v1", "t1" );
s1->setVariable( "v2", "t2" );
context << s1;
QVariantMap m = context.variablesToMap();
QCOMPARE( m.size(), 2 );
QCOMPARE( m.value( "v1" ).toString(), QString( "t1" ) );
QCOMPARE( m.value( "v2" ).toString(), QString( "t2" ) );
QgsExpressionContextScope* s2 = new QgsExpressionContextScope();
s2->setVariable( "v2", "t2a" );
s2->setVariable( "v3", "t3" );
context << s2;
m = context.variablesToMap();
QCOMPARE( m.size(), 3 );
QCOMPARE( m.value( "v1" ).toString(), QString( "t1" ) );
QCOMPARE( m.value( "v2" ).toString(), QString( "t2a" ) );
QCOMPARE( m.value( "v3" ).toString(), QString( "t3" ) );
}
QGSTEST_MAIN( TestQgsExpressionContext )
#include "testqgsexpressioncontext.moc"