2

I am working on a script where I want the user to add feature to a layer in edit mode, and then decide whether to keep the newly added feature in the layer or not. I am doing it the following way:

layer.featureAdded.connect(store_feature_id)
def store_feature_id(feature_id):
 featureIter = 
 layer.getFeatures(QgsFeatureRequest().setFilterFid(feature_id))
 for feat in featureIter:
 feature = feat
 reply = QMessageBox.question(iface.mainWindow(),
 'Save Changes?',
 "Save your changes?",
 QMessageBox.Yes, QMessageBox.No) 
 if reply == QMessageBox.Yes:
 layer.updateFeature(feature)
 layer.commitChanges()

The problem I have is that the command layer.commitChanges will trigger the layer.featureAdded condition again, thus this program will run in an endless loop. I am not sure why, because I expected that the feature add event to only emit once when the feature is initially added to the layer.

This problem can probably be solved by using an extra bool variable as flag, but I am wondering if there is a more elegant solution using the available pyqgis functions?

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Dec 11, 2018 at 20:55
3
  • 1
    I think you need to add an indent from line 7 to the end Commented Dec 11, 2018 at 21:58
  • Let me know if i am missing something here, but in my opinion it will not make a difference, because there will only be one feature returned by the feature iterator, since I am searching for feature by id which is unique. Commented Dec 12, 2018 at 7:01
  • I see that now and agree that it will not make a difference. Joseph's answer looks promising. Commented Dec 12, 2018 at 15:57

1 Answer 1

1

Not sure if it is more elegant but a fairly simple method would be to disconnect the function from the signal immediately when executed and then reconnect it again at the end:

layer.featureAdded.connect(store_feature_id)
def store_feature_id(feature_id):
 # Disconnect function
 layer.featureAdded.disconnect(store_feature_id)
 featureIter = layer.getFeatures(QgsFeatureRequest().setFilterFid(feature_id))
 for feat in featureIter:
 feature = feat
 reply = QMessageBox.question(iface.mainWindow(),
 'Save Changes?',
 "Save your changes?",
 QMessageBox.Yes, QMessageBox.No) 
 if reply == QMessageBox.Yes:
 layer.updateFeature(feature)
 layer.commitChanges()
 # Reconnect function
 layer.featureAdded.connect(store_feature_id)
answered Dec 12, 2018 at 10:57

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.