Nowadays : QGIS 3.x
- Get the layer reference:
layer = iface.activeLayer()
- Select features by expression:
layer.selectByExpression("\"ogc_fid\"=482")
Before QGIS 2.16
Follow these steps:
- Get the layer reference:
cLayer = iface.mapCanvas().currentLayer()`
- Get a featureIterator from an expression:
expr = QgsExpression( "\"ogc_fid\"=482" )
it = cLayer.getFeatures( QgsFeatureRequest( expr ) )
- Build a list of feature Ids from the result obtained in 2:
ids = [i.id() for i in it]`
- 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) )
"\"ogc_fid\"=482 AND name=\"hello world\""? Here it says that this isn't available in python: https://qgis.org/api/classQgsExpression.html#a056130107ebe0f5afdf298b4a93c5ac2. Maybe you know of a way to circumvent this limitation? – Jenia Ivanov May 28 '16 at 17:38"\"ogc_fid\"=482 AND \"name\"='hello world'". BTW, the link you included in your comment is actually stating that the static attributeBinaryOperatorTextis not available in Python bindings, but operators do work forQgsExpression, even if they're used through Python bindings. – Germán Carrillo May 28 '16 at 20:25expr = 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 '16 at 15:53