5

What is the new expression of setSelectedFeatures in PyQGIS 3.0 ? I wrote the following code:

def verCode(layername):
  layer = QgsProject.instance().mapLayersByName(layername)[0]    
  selection= layer.getFeatures(QgsFeatureRequest().setFilterExpression('"CODE_MERC" is NULL'))
  layer.setSelectedFeatures([s.id() for s in selection])
  iface.mapCanvas().zoomToSelected()

1 Answer 1

8

According to the pyqgis api documentation there is a method

layer.selectByIds([s.id() for s in selection])

And for some performance improvements and good practice, don't request any attributes or geometry, if you only need the feature id

request = QgsFeatureRequest(QgsExpression('"CODE_MERC" is NULL')).setFlags(QgsFeatureRequest.NoGeometry).setSubsetOfAttributes([])
selection = layer.getFeatures(request)
4
  • Many thanks Matthias. It is very helpful. However, for the QgsFeatureRequest expression, I receive an error : TypeError: QgsFeatureRequest(): arguments did not match any overloaded call. Perhaps, I wrote it in the wrong way in my code. Could you please write it explicitly in my code?
    – ennine
    Sep 22, 2018 at 9:14
  • It probably was an error on my side. Does it work if you do QgsFeatureRequest(QgsExpression('"CODE_MERC" IS NULL')).setFlags(... Sep 22, 2018 at 9:35
  • No error but nothing happen. I am sorry, but I did not know where to place the obtained "request" in the code. Note that "request" expression is not attached to any layer.
    – ennine
    Sep 22, 2018 at 10:29
  • I updated the sample, is it better now? Btw, nothing should change, it's just "good practice" to request only what is actually needed. Sep 24, 2018 at 6:09

Your Answer

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

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