20

How can I select features with PyQGIS using an expression?

I tried to use an QgsExpression but the select method doesn't take it:

exp = QgsExpression("'ogc_fid' = 482")
cLayer = canvas.currentLayer()
cLayer.select(exp)

Is it possible and if so, how do I do it?

3 Answers 3

43

Nowadays : QGIS 3.x

  1. Get the layer reference:
  layer = iface.activeLayer()
  1. Select features by expression:
  layer.selectByExpression("\"ogc_fid\"=482")

Before QGIS 2.16

Follow these steps:

  1. Get the layer reference:
   cLayer = iface.mapCanvas().currentLayer()`
  1. Get a featureIterator from an expression:
   expr = QgsExpression( "\"ogc_fid\"=482" )
   
   it = cLayer.getFeatures( QgsFeatureRequest( expr ) )
  1. Build a list of feature Ids from the result obtained in 2:
   ids = [i.id() for i in it]`
  1. Select features with the ids obtained in 3:
   cLayer.setSelectedFeatures( ids )

NOTE: If you want to set an expression with a string value, you need to add quotation marks to such value, in this way:

expr = QgsExpression( " \"name\" = 'my string' " )

If your string value comes from a variable, you can do this:

myVariable = 'my string'
expr = QgsExpression( " \"name\" = '{}' ".format(myVariable) )
4
  • How do I say "\"ogc_fid\"=482 AND name=\"hello world\""? Here it says that this isn't available in python: qgis.org/api/…. Maybe you know of a way to circumvent this limitation? May 28, 2016 at 17:38
  • 3
    Keep in mind that field names must be double quoted, string values single quoted, and numbers don't need quotes. In your example: "\"ogc_fid\"=482 AND \"name\"='hello world'". BTW, the link you included in your comment is actually stating that the static attribute BinaryOperatorText is not available in Python bindings, but operators do work for QgsExpression, even if they're used through Python bindings. May 28, 2016 at 20:25
  • @GermánCarrillo I'm using your method above but can't get it to return any values, despite having copy & pasted a known value to search for. The column contains strings, so I have used expr = QgsExpression("\"police_ref\" = 'P0580996'"). I have tried adding a break-character to the search term (for the single-quotes) but it doesn't make a difference. Interestingly, if I open the attribute table I'm querying, and use the expression builder there, it does make a selection if the police_ref I use as an example is in the very first row, but not otherwise
    – Alex
    Jun 27, 2016 at 15:53
  • @GermánCarrillo sorry never mind that, I'm not sure what I did differently but I can get it to select features now! For others reading, you don't need a break-character for the single quotes
    – Alex
    Jun 27, 2016 at 16:14
7

This worked for me from the QGIS Python Console

layer = qgis.utils.iface.activeLayer()
layer.selectByExpression(" \"ogc_fid\" = '{}' ".format(482))
1
  • 2
    Welcome to GIS SE. As a new user, please take the Tour. The existing (and accepted) answer is far more complete. How does this improve upon that? Generally, the way to earn reputation points is to answer unanswered questions, but a new complete answer to a three year old question would be welcome if it specifically addresses a problem with the previous solution (in which case, the problem should certainly be mentioned).
    – Vince
    Dec 27, 2018 at 16:56
3

You only need to test it in the GUI interface: "Select by Expression". If it works, you can paste it in your Python code surrounded by double quotes "".

exp = QgsExpression("ogc_fid=482")

If you compare to a string, you can add single quote ''.

exp = QgsExpression("ogc_fid='482'")

It's the same principle in Python, it can make the difference between double quote and single quote. More information can be found here: Difference between quotation marks ('single' vs "double") in QGIS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.