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

Ujaval Gandhi ujaval at spatialthoughts.com
Sat Dec 11 23:07:11 PST 2021


Try calling layer.commitChanges() after changing the geometry.
[image: Logo] <https://spatialthoughts.com/>
Ujaval Gandhi
Spatial Thoughts
mobile: +91-8095684687
email: ujaval at spatialthoughts.com
[image: LinkedIn icon] <https://www.linkedin.com/in/spatialthoughts/>  [image:
Twitter icon] <https://twitter.com/spatialthoughts>



On Sat, Dec 11, 2021 at 6:55 PM 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?
>
> Cheers,
> Erik
> _______________________________________________
> QGIS-Developer mailing list
> QGIS-Developer at lists.osgeo.org
> List info: https://lists.osgeo.org/mailman/listinfo/qgis-developer
> Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-developer
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20211212/72789831/attachment.html>


More information about the QGIS-Developer mailing list