Index de l'article

Filter/Select

Select features

myPath = r'C:\\Users\\georg\\Downloads\\'
 
project = QgsProject.instance()
project.removeAllMapLayers()
project.clear()
iface.mapCanvas().refresh()
 
myLayer = QgsVectorLayer(myPath + 'peaks_selection/peaks_selection.shp', 'Sommets', 'ogr')
QgsProject.instance().addMapLayer(myLayer)
 
# SELECT
myExpr = u"NAME LIKE '{}'".format('Grand Pic de la Meije')
mySelect = myLayer.getFeatures(QgsFeatureRequest().setFilterExpression(myExpr))
 
myLayer.selectByIds([f.id() for f in mySelect])

Select function

def SelectAndZoom(layername, field, value):
    mylayer = QgsProject.instance().mapLayersByName(layername)[0]
    myselect = mylayer.getFeatures( QgsFeatureRequest().setFilterExpression ( u'"%s" = \'%s\'' % (field, value)) )
    mylayer.selectByIds( [ f.id() for f in myselect ] )
    iface.mapCanvas().zoomToSelected(mylayer)

Then use it like that:

SelectAndZoom('My layer', 'My field', 'Some value')

Select features after click on another layer

layer_selected = QgsProject.instance().mapLayersByName("decathlon_france")[0]
layer_to_select = QgsProject.instance().mapLayersByName("iso_iris")[0]
 
def SelectionAuto():
    selected_features = layer_selected.selectedFeatures()
    for i in selected_features:
        attrs = i.__geo_interface__
        id_mag = i['id']
        # print (id_mag)
 
        myselect = layer_to_select.getFeatures( QgsFeatureRequest().setFilterExpression ( u'"id_mag" = \'%s\'' % id_mag ) )
        layer_to_select.selectByIds( [ f.id() for f in myselect ] )
        # iface.mapCanvas().zoomToSelected(layer_to_select)
 
layer_selected.selectionChanged.connect(SelectionAuto)

Filter a layer

myFilter = u"field_a <> '{}'".format('A value')
myLayer.setSubsetString(myFilter)

Remove a filter

myLayer.setSubsetString('')