4

To get selected features I usually do: layer.selectedFeatures().

Is there a method to retrieve selected features in a list without specifying the layer they belong to ?

I selected features with the "Selection by location" tool:

processing.run("native:selectbylocation", 
                   {'INPUT': "C://path/file1.shp",
                    'PREDICATE':[0,4,7],
                    'INTERSECT':"C://path/file2.shp",
                    'METHOD':0})

The features I am seeking are indeed selected in my QGIS environment. Now I would like to delete them with PyQGIS but I don't know how to retrieve and put them in a list since I didn't create a QgsVectorLayer object for my shapefile.

Do you know a way to either retrieve the selected features or the layer they belong to ?

Taras
  • 32,823
  • 4
  • 66
  • 137
Anthony
  • 133
  • 7
  • 1
    What is the output of the algorithm? Perhaps that will give you a clue – Matt Apr 06 '22 at 15:05
  • The output is a dict object with one key : {"OUTPUT": "C://path/file1.shp"}. So I tried to store that output in a QgsVectorLayer object, but there is 0 selected feature when I try to count them with selectedFeatureCount(). Even though the same layer already displayed in QGIS has some selected features in its attribute table. – Anthony Apr 07 '22 at 08:21

1 Answers1

5

There are most likely several approaches to tackle your issue, but I would probably lean on @Matt's suggestion.

There is a special method for deleting selected features called deleteSelectedFeatures().

Keep in mind that the output of processing will inherit the name of your 'INPUT' variable.

layer1 = QgsProject.instance().mapLayersByName('grid_test2')[0]
layer2 = QgsProject.instance().mapLayersByName('grid_test')[0]

selection = processing.run("native:selectbylocation", {'INPUT': layer1, 'PREDICATE': [0,4,7], 'INTERSECT': layer2, 'METHOD':0})['OUTPUT']

layer_to_edit = QgsProject.instance().mapLayersByName(selection.name())[0]

layer_to_edit.startEditing() layer_to_edit.deleteSelectedFeatures() layer_to_edit.commitChanges()

If you though want to retrieve a list with selected features, then try this:

layer1 = QgsProject.instance().mapLayersByName('grid_test2')[0]
layer2 = QgsProject.instance().mapLayersByName('grid_test')[0]

selection = processing.run("native:selectbylocation", {'INPUT': layer1, 'PREDICATE': [0,4,7], 'INTERSECT': layer2, 'METHOD':0})['OUTPUT']

layer_to_edit = QgsProject.instance().mapLayersByName(selection.name())[0]

selected_ids = [feat.id() for feat in selection.selectedFeatures()]

layer_to_edit.startEditing() for fid in selected_ids: layer_to_edit.deleteFeature(fid) layer_to_edit.commitChanges()


References:

Matt
  • 16,843
  • 3
  • 21
  • 52
Taras
  • 32,823
  • 4
  • 66
  • 137