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?
Answer
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) )
No comments:
Post a Comment