QGIS crashes when doing a rollback after modifying values of an user-added feature with pyQGIS
I answer myself :-) I have found an explanation here http://qgis-developer.osgeo.narkive.com/5wnziigA/wrapping-changeattributevalue-between-begin-and-end-editcommand#post2
Currently it is not safe to do calls that modify vector layer data in slots connected to signals notifying about data change (such as featureAdded). The issue is that at the point when those signals are emitted, their underlying undo commands were not yet pushed onto the stack, so doing further editing calls causes corruption of undo stack (undo command for follow up operation is placed before the first operation).
My workaround consists in delaying the handling of the feature addition using the editCommandEnded slot. This is the relevant code:
def onFeatureAdded(self, fid):
if fid < 0:
self._addedFeatures.append(fid)
def onEditCommandEnded(self):
while self._addedFeatures:
fid = self._addedFeatures.pop()
self._handleAdded(fid)
def _handleAdded(self, fid):
guid_pol = str(uuid4()) # RFC 4122 UUID v4
try:
self.layer.beginEditCommand(u"Assign UUID")
self.layer.changeAttributeValue(fid, self.layer.fieldNameIndex('guid_pol'), guid_pol)
self.layer.endEditCommand()
except:
self.layer.destroyEditCommand()
raise
I hope this helps somebody else.
mhm,
Your answer was really great and solved our problem here. But to fully understand why this happened I how to solve it, I studied QGIS source code and my co-worker and I made an article explaining the problem in detail. Please, feel free to check it!
https://gis4programmers.wordpress.com/2017/02/26/working-properly-with-pyqgqis-edit-buffer-to-enable-undo-commands/