My PyQGIS script works fine if I am not in an edit session, but 99% of the time I will be, so I need it to work whilst in editing mode.
from PyQt5.QtGui import *
layer = QgsProject.instance().mapLayersByName("test")[0]
iface.setActiveLayer(layer)
value='222'
with edit(layer):
for feature in layer.selectedFeatures():
feature['flag1'] = value
layer.updateFeature(feature)
msg = QMessageBox()
msg.setText("All done.")
msg.show()
So basically, it just updates the 'flag1' field with the assigned value for those features that have already been selected from the 'test' layer. How do I make this work inside an edit session? Currently I receive this error:
File "C:/PROGRA~1/QGIS3~1.16/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in enter assert self.layer.startEditing() AssertionError
-
I get: TypeError: 'QgsVectorLayer' object does not support indexing. As I said, the script works, but I need it to work within an edit session.djr_– djr_2020年12月02日 13:43:04 +00:00Commented Dec 2, 2020 at 13:43
1 Answer 1
You can't start a new edit session if the layer is already in one.
You need to test if your layer is in an edit session and if it's the case, don't open a new one. QgsVectorLayer has a method isEditable()
wich returns a boolean, true
if the layer is in an edit session. You can use it to test your layer and know what to do.
This code should work :
from PyQt5.QtGui import *
layer = QgsProject.instance().mapLayersByName("test")[0]
iface.setActiveLayer(layer)
value='222'
if layer.isEditable() :
for feature in layer.selectedFeatures():
feature['flag1'] = value
layer.updateFeature(feature)
else :
with edit(layer):
for feature in layer.selectedFeatures():
feature['flag1'] = value
layer.updateFeature(feature)
msg = QMessageBox()
msg.setText("All done.")
msg.show()
-
additionally, I had a 'check if writable, make readonly' check in my code, whilst using the 'with edit()'. For some reason this really upset the with edit() command, when I removed the check if editable/makereadonly, the code worked. Not sure why though unfortunately, but worth mentioning.nr_aus– nr_aus2022年02月17日 01:30:19 +00:00Commented Feb 17, 2022 at 1:30