1

I have two layers, a polygon_lyr and a line_lyr. I want to use a QgsFeatureRequest() for the line_lyr.getFeatures() but instead of returning the lines which intersect the bounding box of a polygon, I just want the lines which intersect the actual polygon geometry. I assume this is what ExactIntersect flag does. But I do not know how to actually use it.

for i, poly in enumerate(polygon_lyr.getFeatures()):
    poly_geom = poly.geometry()

    for line in line_lyr.getFeatures(QgsFeatureRequest(poly_geom.boundingBox())):
        #processing operations
0

I don't think this is possible as the QgsFeatureRequest() class must use a specified bounding box if you want to add a spatial filter. An example method isQgsFeatureRequest().setFilterRect(boundingBox). The ExactIntersect flag instead uses the actual geometry of the feature for intersection, but it will be used against the bounding box.

The following is an example of using QgsFeatureRequest() where the geometry of each line is intersected with the bounding box of each polygon:

polygon_lyr = QgsProject.instance().mapLayersByName('polygon example')[0]
line_lyr = QgsProject.instance().mapLayersByName('line example')[0]
ids = []

for i, poly in enumerate(polygon_lyr.getFeatures()):
    poly_geom = poly.geometry()
    request = QgsFeatureRequest().setFilterRect(poly_geom.boundingBox()).setFlags(QgsFeatureRequest.ExactIntersect)
    for line in line_lyr.getFeatures(request):
        ids.append(line.id())

line_lyr.selectByIds(ids)

If you want to do an intersection using the line geometries against the polygon geometries, you could do this more directly using:

polygon_lyr = QgsProject.instance().mapLayersByName('polygon example')[0]
line_lyr = QgsProject.instance().mapLayersByName('line example')[0]
ids = []

for i, poly in enumerate(polygon_lyr.getFeatures()):
    poly_geom = poly.geometry()
    for line in line_lyr.getFeatures():
        if line.geometry().intersects(poly_geom):
            ids.append(line.id())

line_lyr.selectByIds(ids)

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.