Skip to content

Commit

Permalink
Add custom hash for QgsFeature
Browse files Browse the repository at this point in the history
Fixes #49932

(cherry picked from commit fc0e97e)
  • Loading branch information
nyalldawson committed Sep 16, 2022
1 parent c547b6a commit 6e50b6d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
5 changes: 5 additions & 0 deletions python/core/auto_generated/qgsfeature.sip.in
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ geometry and a list of field/values attributes.
sipCpp->deleteAttribute( fieldIdx );
%End

long __hash__() const;
%MethodCode
sipRes = qHash( *sipCpp );
%End

QgsFeature( qint64 id = FID_NULL );
%Docstring
Constructor for QgsFeature
Expand Down
7 changes: 6 additions & 1 deletion src/core/qgsfeature.h
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ class CORE_EXPORT QgsFeature
else
sipCpp->deleteAttribute( fieldIdx );
% End

long __hash__() const;
% MethodCode
sipRes = qHash( *sipCpp );
% End
#endif

/**
Expand Down Expand Up @@ -881,7 +886,7 @@ typedef QMap<qint64, QgsGeometry> QgsGeometryMap;

typedef QList<QgsFeature> QgsFeatureList;

uint qHash( const QgsFeature &key, uint seed = 0 ) SIP_SKIP;
CORE_EXPORT uint qHash( const QgsFeature &key, uint seed = 0 ) SIP_SKIP;

Q_DECLARE_METATYPE( QgsFeature )
Q_DECLARE_METATYPE( QgsFeatureList )
Expand Down
26 changes: 26 additions & 0 deletions tests/src/python/test_qgsfeature.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,32 @@ def test_equality(self):
feat2.setFields(fields)
self.assertNotEqual(feat, feat2)

def test_hash(self):
fields = QgsFields()
field1 = QgsField('my_field')
fields.append(field1)
field2 = QgsField('my_field2')
fields.append(field2)

feat = QgsFeature(fields, 0)
feat.initAttributes(1)
feat.setAttribute(0, "text")
feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(123, 456)))

self.assertIsNotNone(hash(feat))

# try a second identical feature, hash should be the same
feat2 = QgsFeature(fields, 0)
feat2.initAttributes(1)
feat2.setAttribute(0, "text")
feat2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(123, 456)))

self.assertEqual(hash(feat), hash(feat2))

# different feature, different hash
feat2.setId(100)
self.assertNotEqual(hash(feat), hash(feat2))

def test_ValidFeature(self):
myPath = os.path.join(unitTestDataPath(), 'points.shp')
myLayer = QgsVectorLayer(myPath, 'Points', 'ogr')
Expand Down

0 comments on commit 6e50b6d

Please sign in to comment.