2

I can rotate polygon features in a shapefile using:

vlayer = iface.activeLayer()
vlayer.startEditing()
for ft in vlayer.getFeatures():
    geom = ft.geometry()
    pt = ft.geometry().centroid().asPoint()
    geom.rotate(45, pt)
    vlayer.dataProvider().changeGeometryValues({ 0 : geom })

vlayer.commitChanges()

But if I use this on a memory layer, nothing happens. True values are printed on the console but the features are not rotated, even after refreshing the canvas and repainting the layer.

Is there a way to do this for memory layers?

4

A recipe for your intent (deduced from answer Qgis 2.7 (Dev) feature rotation?)

rotation = 45
vlayer = iface.activeLayer()
provider = vlayer.dataProvider()

couples_id_geom = []
for feature in vlayer.getFeatures():
    geom = feature.geometry()
    centroid = feature.geometry().centroid().asPoint()
    geom.rotate(rotation, centroid)
    # accumulate args to avoid rotation feature by feature
    couples_id_geom.append([feature.id(), geom])

# Change the layer features rotation in one go
provider.changeGeometryValues({
  couple_id_geom[0]: couple_id_geom[1] for couple_id_geom in couples_id_geom
})

# Refresh to see the changes
vlayer.triggerRepaint()
1
  • Great, this works. Cheers! – user35594 Jul 27 '20 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.