3

In QGIS 3.10, I have layers in which I select features by location (to find duplicates), using :

selected_features = processing.run('qgis:selectbylocation', {'INPUT':layer1, 'PREDICATE':0, 'INTERSECT':layer2, 'METHOD':0})

'METHOD':0 means I begin a new selection with the selected features

Then, in this selection, I want to select features by expression, using :

subselected_features = processing.run('qgis:selectbyexpression', {'INPUT':layer1, 'EXPRESSION':expression, 'METHOD':3})

'METHOD':3 means I select features in the current selection

Now, I want to delete all the subselected features. I know how to delete features by expression, with the method explained here (Deleting selected features using PyQGIS?) :

with edit(layer1):
 # build a request to filter the features based on an attribute
 request = QgsFeatureRequest().setFilterExpression('"DN" != 3')
 # we don't need attributes or geometry, skip them to minimize overhead.
 # these lines are not strictly required but improve performance
 request.setSubsetOfAttributes([])
 request.setFlags(QgsFeatureRequest.NoGeometry)
 # loop over the features and delete
 for f in layer1.getFeatures(request):
 layer1.deleteFeature(f.id())

But this way selects features in the entire layer1. It does not allow to choose a METHOD as with processing, to make a subselection in the current selection.

Does someone has an idea to delete these subselected features ?

asked Mar 25, 2020 at 10:18
4
  • You should change edit(layer) into edit(layer1). Then, I think, it will work. Commented Mar 25, 2020 at 11:30
  • Thanks for the help. It was just an error in the code i copied, but not the source of the problem. I edited the post to correct it. Ben W answer is simply what i needed Commented Mar 25, 2020 at 12:09
  • I've QGIS 3.8. Your script worked in it. It might have been the problem. Commented Mar 25, 2020 at 12:13
  • The script works, but it does not fill my need. It selects features to delete in the whole layer, whereas I wanted to select features within the current selection. Commented Mar 25, 2020 at 12:49

1 Answer 1

6

If the features you want to delete are already selected it should be as simple as:

with edit(layer1):
 layer1.deleteSelectedFeatures()

As per the method of QgsVectorLayer class from the docs here.

answered Mar 25, 2020 at 11:12
0

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.