[GIS] Intersection and add selection in pyqgis

pyqgis

I'm trying to add the intersected geometries of 2 layers in PyQGIS.

I have a grid made up by cells (polygons) and a line layer. I want to select the features of the grid layer where they intersect the line features (so basically the Select by Location tool used within a Python script).

The code (that works) is the following:

# get the layers from the interface
grid = iface.activeLayer()
line = iface.activeLayer()

for i in grid.getFeatures():
    for l in line.getFeatures():
        if i.geometry().intersects(l.geometry()):
            print i

It returns (correctly) 17 features.

What I'm not able to to is to add these QgsFeatures as a selection to the grid layer.

Best Answer

Sorry, guys.. I've tried everything but not the easiest solution:

# get the layers from the interface
grid = iface.activeLayer()
line = iface.activeLayer()

for i in grid.getFeatures():
    for l in line.getFeatures():
        if i.geometry().intersects(l.geometry()):
        # add the selection to the layer
            grid.select(i.id())
Related Question