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()
1

1 Answer 1

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:

3
  • Thanks for the sugestion @Taras. It worked fine and did exactly what I wanted it to do perfectly!
    – Is.Ballad
    Commented Jun 25, 2023 at 1:35
  • 3
    @Is.Ballad please mark the question accepted!
    – til_b
    Commented Aug 29, 2023 at 8: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
    Commented Aug 31, 2023 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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