[QGIS-Developer] pyqgis getFeatures(<FilterExpression>) doesn't always fetch modified geometry

Nyall Dawson nyall.dawson at gmail.com
Sun Dec 12 14:33:24 PST 2021


On Sat, 11 Dec 2021 at 23:25, Erik Polzin <eriktpol at gmail.com> wrote:
>
> Hi all,
>
> Noticed some strange behaviour in QGIS' Python API the other day.
> I needed to get a subset of points from a memory layer of point features, and had previously done so by calling getFeatures(), and then filtering this iterable in Python. I thought I could speed it up by using a filter expression directly to let c++ do the filtering instead, but was surprised to see that now the geometry wasn't up to date with the memory layer's edit buffer.
>
> I've replicated the behaviour it in a small script here:
>
> from qgis.core import QgsVectorLayer, QgsField, QgsGeometry, QgsPointXY, QgsFeature
> from PyQt5.QtCore import QVariant
>
> layer = QgsVectorLayer("Point", "test", "memory")
> pr = layer.dataProvider()
> pr.addAttributes([QgsField("name", QVariant.String)])
> layer.updateFields()
>
> initialGeom = QgsGeometry.fromPointXY(QgsPointXY(0, 0))
> f = QgsFeature()
> f.setGeometry(initialGeom)
> f.setAttributes(["Tom"])
> added, (f,) = layer.dataProvider().addFeatures([f])
>
> layer.startEditing()
> editedGeom = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
> layer.changeGeometry(f.id(), editedGeom)
> layer.changeAttributeValues(f.id(), {0: "Harry"})
>
> for f in layer.getFeatures():
>     print(f.id(), f.attributes(), f.geometry())
>
> for f in layer.getFeatures("name = 'Harry'"):
>     print(f.id(), f.attributes(), f.geometry())
>
> # >>> Prints different results!
>
> This only seems to happen with both calls to changeGeometry and changeAttributeValues.
> Is there some way of getting around this? Would it be classified as a bug in the API?

Thanks for the detailed write up! A fix has been submitted here:
https://github.com/qgis/QGIS/pull/46449

Nyall


More information about the QGIS-Developer mailing list