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])
asked Apr 25, 2019 at 8:23
1

1 Answer 1

2

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])
answered Apr 25, 2019 at 12:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.