I have a layer which has one feature. I try to move the feature(multipolygon) using the script below:
layer = iface.activeLayer()
for feat in layer.getFeatures():
prev_pos = feat.geometry().centroid().asPoint()
success = feat.geometry().translate(100, 100) # translation
next_pos = feat.geometry().centroid().asPoint()
print(success)
print(prev_pos)
print(next_pos)
But I get different results in QGIS 2 and QGIS 3. (The multipolygon has many points, therefore, I printed out only its centroid)
Output in QGIS 2:
0 # means operation succeeded
(552084,433685)
(552184,433785) # changed coordinates
Output in QGIS 3:
0 # means operation succeeded
<QgsPointXY: POINT(552084 433685)>
<QgsPointXY: POINT(552084 433685)> # same coordinates
When I try to move a point feature, I get same results.
Why does not translate
method move the feature in QGIS 3? What am I missing?
EDIT: If I create a QgsGeometry
object manually, translate
method works correctly in QGIS 3.
points = [QgsPointXY(0,0), QgsPointXY(2,0), QgsPointXY(2,2), QgsPointXY(0,2)]
geom = QgsGeometry.fromMultiPolygonXY( [ [points] ] )
print(geom)
geom.translate(100, 100)
print(geom)
Output in QGIS 3:
<QgsGeometry: MultiPolygon (((0 0, 2 0, 2 2, 0 2, 0 0)))>
<QgsGeometry: MultiPolygon (((100 100, 102 100, 102 102, 100 102, 100 100)))>