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?

  • 1
    I think you need to add an indent from line 7 to the end – jbalk Dec 11 '18 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. – Ending Dec 12 '18 at 7:01
  • I see that now and agree that it will not make a difference. Joseph's answer looks promising. – jbalk Dec 12 '18 at 15:57
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)

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.