7

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?

9

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.

5

After selecting the features, 'Zoom to Selection' can also be done by the following code:

eMenu = self.iface.viewMenu()
eMenu.actions() [12].trigger()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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