Moving a geometry using PyQGIS3
To change QgsFeature
geometry in QGIS 3 you have to call setGeometry()
explicitly.
geom = feat.geometry()
geom.translate(100, 100)
feat.setGeometry(geom)
Explanation:
In QGIS 2 geometry()
returns a pointer, so it can be modified in place.
QgsGeometry* QgsFeature::geometry() //QGIS 2
In QGIS 3 geometry()
returns value instead of a pointer. Additionally it is const now, so it is not allowed to modify the QgsFeature
.
QgsGeometry QgsFeature::geometry() const //QGIS 3
(see https://qgis.org/api/2.18/classQgsFeature.html#ab0a934a1b173ce5ad8d13363c20ef3c8)
In your examples the manipulated geometry is not written back to data source. The Python Cookbook for PyQGIS offers two possibilities:
(1) using te methods changeAttributeValues()
, changeGeometryValues()
of the dataProvider
(2) do that within an editing buffer, to have the possibility to explicte save in an commit and so on.
a solution for (1) based on your script:
layer = iface.activeLayer()
for feat in layer.getFeatures():
geom = feat.geometry()
print(geom.asWkt())
success = geom.translate(100, 100) # translation
fid = feat.id()
print('id:',fid)
layer.dataProvider().changeGeometryValues({ fid : geom })
# reread geoms to see if they changed
for feat in layer.getFeatures():
geom = feat.geometry()
print(geom.asWkt())