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()
ennine
  • 863
  • 2
  • 10
  • 20

1 Answers1

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)
Matthias Kuhn
  • 27,780
  • 3
  • 88
  • 129
  • 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 '18 at 09:14
  • It probably was an error on my side. Does it work if you do QgsFeatureRequest(QgsExpression('"CODE_MERC" IS NULL')).setFlags(... – Matthias Kuhn Sep 22 '18 at 09: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 '18 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. – Matthias Kuhn Sep 24 '18 at 06:09