[GIS] How to select and zoom in features from a QGIS Python Plugin

pyqgispythonqgisqgis-pluginsselect-by-attribute

I'm very new to Python. I'm trying to find a way to select and zoom to the features from a QGIS layer.

I've created a plugin and built a custom form. I have 3 values from the form which I need to place in a query but as I'm new, I don't know how.

aExchange = self.dlg.EXCHANGE_1141_CODE.currentText()
aPCP = self.dlg.BT_OBJECT_CLASS.currentText()
aObject = self.dlg.BT_OBJECT_ID.text()

The filter on the Attribute table is like this:

"EXCHANGE_1141_CODE" = 'IH' AND "BT_OBJECT_CLASS" = 'PCP' AND "BT_OBJECT_ID" = '10' 

I've tried:

alayer.SetSubSetString ('EXCHANGE_1141_CODE = \'IH\'') 

but this seems to just change the filter on the layer source which isn't what I want.

I want to be able to search for a feature and go to it. How can I do it with PyQGIS?

Best Answer

Follow these 5 steps in the QGIS Python console:

  1. Get the layer reference (I assume the layer is at the top of the ToC):

    l = iface.mapCanvas().layers()[0]

  2. Get a featureIterator from an expression:

    expr = QgsExpression( "\"EXCHANGE_1141_CODE\"='IH'" ) it = l.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.:

    l.setSelectedFeatures( ids )

  5. Zoom to selected features:

    iface.mapCanvas().zoomToSelected()

I've tested this procedure in QGIS v.2.6.