Skip to content

Commit

Permalink
Add method to QgsAttributes to convert to QgsAttributeMap
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Nov 8, 2016
1 parent f9bb230 commit 6f3b0ca
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/core/qgsfeature.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down Expand Up @@ -327,3 +344,4 @@ uint qHash( const QgsFeature& key, uint seed )

return hash;
}

8 changes: 8 additions & 0 deletions src/core/qgsfeature.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ class CORE_EXPORT QgsAttributes : public QVector<QVariant>
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 ); }
};

Expand Down
23 changes: 23 additions & 0 deletions tests/src/core/testqgsfeature.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 6f3b0ca

Please sign in to comment.