Sunday, 9 June 2019

qgis - How to select features using an expression with pyqgis?


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:




  1. Get the layer reference:


    cLayer = iface.mapCanvas().currentLayer()





  2. Get a featureIterator from an expression:


    expr = QgsExpression( "\"ogc_fid\"=482" )


    it = cLayer.getFeatures( QgsFeatureRequest( expr ) )




  3. Build a list of feature Ids from the result obtained in 2.:


    ids = [i.id() for i in it]





  4. 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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...