[GIS] “Select by Attribute” in QGIS using python

pyqgisqgis

Is there a way to use the function "Select by Attribute" in QGIS using a python command? In my plugin the user should enter a value via a GUI and this value should be used in a function which selects all features which have this attribute. The column name is fixed in the code, the function should only search for the correct value.

In my current solution the function connects QGIS to a PostgreSQL database and runs an SQL statement. This creates a table from the result and the table is visualised as Shapefile in QGIS.

In principal it would be enough to highlight the features and not to create a new Shapefile of the selection. Using the "Select by Attribute" function would also skip the unnecessary database connection.

Is there a way to use the function "Select by Attribute" in python so that the features are highlighted? Using the function in QGIS all features that doesn't match the query are temporary blanked-out that would be ok too.

Best Answer

Starting from QGIS 2.2 this is supported in a very natural way. It can be done via the QGIS expression engine using the QgsFeatureRequest.setFilterExpression( unicode ) method.

# The important part: get the feature iterator with an expression
it = l.getFeatures( QgsFeatureRequest().setFilterExpression ( u'"Counties" = \'Norwich\'' ) )
# Set the selection
l.setSelectedFeatures( [ f.id() for f in it ] )

The best thing about it: if you have a recent QGIS version (2.10 and later), this will be filtered directly in the database so much more performant than other solutions while still being very readable.

Related Question