2

I'm working on a vector layer where I have to merge all n+i [id] attributes into entity(n)[id] where entities(n+i)[id] equals the entity(n)[id], then delete all n+i entities. All works fine but I call several times startEditing functions before commiting changes, and my question is: does calling commitChanges closes startEditing, or does it let it opened, like if it was a file descriptor or a pointer which we needed to free after the job's done?

The code is:

  olayer.startEditing()
  olayer.changeAttributeValue(n,id_obj,id_obj_sum,NULL,True)
  olayer.commitChanges()
  olayer.startEditing()
  i= i-1
  while i >=1:
   olayer.deleteFeature(n+i)
   i=i-1

  olayer.commitChanges()

As you can see, we call several times olayer.startEditing, even more because all that code is in while body... So will that spawn hordes of startEditing "pointers" or will it just continuously set the olayer editable status as "open to edition" ?

Actually the code works, but it's painfully slow, is this the reason why ?

1 Answers1

3

By and large, you should not start the edit mode more than once in your layer.

You can commit at the end of all your changes to the layer, so that your modifications stay in an edit buffer in the meantime.

QgsVectorLayer.commitChanges() can let the edit mode open if you pass a False as parameter (the parameter is called stopEditing, see the docs). Like this:

# If the commit is sucessful, let the edit mode open
layer.commitChanges(False)  

Also, have a look at the with edit(layer): syntax in the QGIS docs. Using such syntax you avoid starting/committing/closing the edit mode, QGIS does it for you.

with edit(layer):
    # All my layer modifications here

# When this line is reached, my layer modifications are already committed.
Germán Carrillo
  • 202
  • 2
  • 12
  • Ok, i see.. Commiting changes without closing editing would be a good idea, with the false option then, so it frees the editing buffer. Because working on humongous numbers of rows and stacking changes to do would overcome the "edit buffer" or the kind of thing that works as. Thanks! – Fred Farfart Jun 22 '21 at 20:12
  • 1
    Do you happen to know how we say "thanks" in Stack Overflow? :) – Germán Carrillo Jun 22 '21 at 20:31
  • Hi, How do you say thanks in Stack Overflow??? – nanunga Feb 09 '23 at 14:34