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?
-
1I think you need to add an indent from line 7 to the endjbalk– jbalk2018年12月11日 21:58:04 +00:00Commented 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.Ending– Ending2018年12月12日 07:01:15 +00:00Commented Dec 12, 2018 at 7:01
-
I see that now and agree that it will not make a difference. Joseph's answer looks promising.jbalk– jbalk2018年12月12日 15:57:32 +00:00Commented Dec 12, 2018 at 15:57
1 Answer 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)