diff --git a/src/core/qgsfeature.cpp b/src/core/qgsfeature.cpp index 6aa6f4da59e..fd9137de8c4 100644 --- a/src/core/qgsfeature.cpp +++ b/src/core/qgsfeature.cpp @@ -29,6 +29,23 @@ email : sherman at mrcc.com * See details in QEP #17 ****************************************************************************/ + +QgsAttributeMap QgsAttributes::toMap() const +{ + QgsAttributeMap map; + for ( int idx = 0; idx < count(); ++idx ) + { + QVariant v = at( idx ); + if ( v.isValid() ) + map.insert( idx, v ); + } + return map; +} + +// +// QgsFeature +// + QgsFeature::QgsFeature( QgsFeatureId id ) { d = new QgsFeaturePrivate( id ); @@ -327,3 +344,4 @@ uint qHash( const QgsFeature& key, uint seed ) return hash; } + diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index ef7e71cc194..0c2d51b796e 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -107,6 +107,14 @@ class CORE_EXPORT QgsAttributes : public QVector return true; } + /** + * Returns a QgsAttributeMap of the attribute values. Null values are + * excluded from the map. + * @note added in QGIS 3.0 + * @note not available in Python bindings + */ + QgsAttributeMap toMap() const; + inline bool operator!=( const QgsAttributes &v ) const { return !( *this == v ); } }; diff --git a/tests/src/core/testqgsfeature.cpp b/tests/src/core/testqgsfeature.cpp index 5536a87ec24..5f756c9adc6 100644 --- a/tests/src/core/testqgsfeature.cpp +++ b/tests/src/core/testqgsfeature.cpp @@ -33,6 +33,7 @@ class TestQgsFeature: public QObject void init();// will be called before each testfunction is executed. void cleanup();// will be called after every testfunction. void attributesTest(); //test QgsAttributes + void attributesToMap(); void create();//test creating a feature void copy();// test cpy destruction (double delete) void assignment(); @@ -120,6 +121,28 @@ void TestQgsFeature::attributesTest() QCOMPARE( attr7.size(), 5 ); } +void TestQgsFeature::attributesToMap() +{ + QgsAttributes attr1; + attr1 << QVariant( 5 ) << QVariant() << QVariant( "val" ); + QgsAttributeMap map1 = attr1.toMap(); + + QCOMPARE( map1.count(), 2 ); + QCOMPARE( map1.value( 0 ), QVariant( 5 ) ); + QCOMPARE( map1.value( 2 ), QVariant( "val" ) ); + + QgsAttributes attr2; + attr2 << QVariant() << QVariant( 5 ) << QVariant(); + QgsAttributeMap map2 = attr2.toMap(); + + QCOMPARE( map2.count(), 1 ); + QCOMPARE( map2.value( 1 ), QVariant( 5 ) ); + + QgsAttributes attr3; + QgsAttributeMap map3 = attr3.toMap(); + QVERIFY( map3.isEmpty() ); +} + void TestQgsFeature::create() { //test constructors