Geographic Information Systems Asked by djr_ on May 13, 2021
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/./pythonqgiscoreadditionsedit.py",
line 38, in enter
assert self.layer.startEditing() AssertionError
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()
Correct answer by JULESG on May 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP