1

I am testing a script that add features from one *.shp file to another. But also I need to wait for user to save or discard changes. But it seems that adding features from script using dataProvider() automatically commit changes without waiting for user to do it. Here is my code

layer_first = QgsProject.instance().mapLayersByName(u'layer_first')[0]
layer_second = QgsProject.instance().mapLayersByName(u'layer_second')[0]
feat = [n.geometry() for n in layer_first.getSelectedFeatures()][0]
f_pnt = QgsFeature()
f_pnt.setGeometry(feat)

layer_second.startEditing()
layer_second.dataProvider().addFeatures([f_pnt])

I tried:

layer_second.rollback(True) # doesn't work

qgis.utils.iface.actionRollbackEdits().trigger() # also doesn't work

with edit(layer_second): # works only from edit session which is not preferrable
    layer_second.dataProvider().addFeatures([f_pnt])
1

Already found the solution. Maybe for someone it will be helpful in future. I found that a new feature should be created completely from "zero point". In my code I just created a new QgsFeature() and add geometry there. But it seems that feature is missing attributes, however feature can be added even without them. So I miss attributes that can be taken directly from the original. Eventually when geometry and attributes are set, the feature can be loaded into layer and discarding changes will work. Final code:

layer_first = QgsProject.instance().mapLayersByName(u'layer_first')[0]
layer_second = QgsProject.instance().mapLayersByName(u'layer_second')[0]
feat = [n for n in layer_first.getSelectedFeatures()][0]
f_pnt = QgsFeature()
f_pnt.setGeometry(feat.geometry())
f_pnt.setAttributes(feat.attributes())

layer_second.startEditing()
layer_second.dataProvider().addFeatures([f_pnt])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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