2

Using python I would like to iterate through a point layer and select from a line layer each line that touches a particular point. To try and familiarize myself with selecting items with python I'm just trying to write a script that selects lines that touch the selected point. This is what I have but I only get "AttributeError: 'list' object has no attribute 'selectedFeatures'".

layer_select = QgsProject.instance().mapLayersByName('Points')
layer_to_select = QgsProject.instance().mapLayersByName('Lines')
for selected_feat in layer_select.selectedFeatures():
    to_select = []
    for feat_to_select in layer_to_select.getFeatures():
        if feat_to_select.geometry().intersects(selected_feat.geometry()):
            to_select.append(feat_to_select.id())
    layer_to_select.setSelectedFeatures(to_select)
2

A little digging and I found what works.

layers = QgsProject.instance().mapLayersByName('point')
layer_select = layers[0] # first layer named LAYER_NAME.

layers = QgsProject.instance().mapLayersByName('line')
layer_to_select = layers[0] # first layer named LAYER_NAME.

for f in layer_select.selectedFeatures():
    geom = f.geometry()
    to_select = []
    for feat_to_select in layer_to_select.getFeatures():
        if feat_to_select.geometry().intersects(geom):
            to_select.append(feat_to_select.id())
    layer_to_select.selectByIds(to_select)

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.