5

I have a layer containing several small square geometries in QGIS. I want to tilt these ones by one to the same angle. So I wrote the following Python code for that, but it does not work properly. Could you please give me some suggestions for improvement?

#import processing

layer_name = "my_layer"

layer = QgsProject.instance().mapLayersByName(layer_name)[0]

features = layer.getFeatures()

for feature in features: geometry = feature.geometry() center = geometry.centroid().asPoint() rotated_geometry = geometry.rotate(33, center) feature.setGeometry(rotated_geometry) layer.updateFeature(feature)

layer.updateExtents()

Taras
  • 32,823
  • 4
  • 66
  • 137
Is.Ballad
  • 51
  • 1

1 Answers1

12

There are several things that I would improve:

  • do not forget to start/startEditing, end/endEditCommand(), and commit/commitChanges() editings

  • use the setGeometry() method properly, otherwise the result of it will be just GeometryOperationResult.Success

  • make your code homogeneous

     layer = QgsProject.instance().mapLayersByName("polygon")[0]
     ...
         geometry.rotate(33, center)
    

    or

     layer_name = "polygon"
     angle = 33
    

    layer = QgsProject.instance().mapLayersByName(layer_name)[0] ... geometry.rotate(angle, center)

  • use for feature in layer.getFeatures() in one line

  • import only classes that are deployed, no need for the import processing

  • the hasGeometry() method of the QgsFeature class can be useful

In the end, your code may look as follows:

from qgis.core import QgsProject

layer = QgsProject.instance().mapLayersByName("my_layer")[0]

layer.startEditing()

for feature in layer.getFeatures(): while feature.hasGeometry(): geometry = feature.geometry() center = geometry.centroid().asPoint() geometry.rotate(33, center) feature.setGeometry(geometry) layer.updateFeature(feature) break

layer.endEditCommand() layer.commitChanges()

Note: Remember that applied changes can not be undone.

Another approach can be found in the references.


References:

Taras
  • 32,823
  • 4
  • 66
  • 137
  • Thanks for the sugestion @Taras. It worked fine and did exactly what I wanted it to do perfectly! – Is.Ballad Jun 25 '23 at 01:35
  • 3
    @Is.Ballad please mark the question accepted! – til_b Aug 29 '23 at 08:01
  • Is the endEditCommand() really necessary? I have never seen it used and the commitChanges() specifically has a stopEditing parameter. And if you are going to commit the changes straight away why bother manually stopping the edit block, even the qgis.core.edit(layer) with statement block of qgis calls commitChanges() directly. also why do a while break where a simple if would do ? – Kalak Aug 31 '23 at 07:41