10

I want to create a function that selects a feature and zooms to it (similar in QGIS). Therefore there is following function:

QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)

def zoomTo(self):
    layer = self.vlayer
    atable = self.ui.table

    selectList=[]
    for i in atable.selectionModel().selectedRows():
        ID = atable.item(i.row(),0).text()
        selectList.append(int(ID))

    layer.setSelectedFeatures(selectList)

The selected features are highlighted on the map. But I have no idea how to make a "zoom" to the selected features or some kind of focus them in the middle of the map.

13

You need to set the extents of the map canvas to the extents of the selections:

box = layer.boundingBoxOfSelected()
iface.mapCanvas().setExtent(box)
iface.mapCanvas().refresh()
  • Thank you! And how can i relate the iface to the actual open QGIS map? – Martin Jul 11 '13 at 13:42
  • Are you working on a plugin, or a standalone app? – Nathan W Jul 11 '13 at 13:48
  • Yes got it. I am working on a plugin. I forgot the gis.utils.iface. Now its working perfectly. Thank you again! – Martin Jul 11 '13 at 13:50
5

Zoom to selected features can also be performed by triggering the "Zoom to Selection" option of View menu.

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

Note: The index number may vary with different QGIS versions.


Or more directly:

iface.actionZoomToSelected().trigger()
  • 1
    I would not use this method. What if in a new qgis version the functions moves to index 13? Troubleshooting these kind of issues is definitely not very fun... – mozzbozz Aug 7 '17 at 7:34
  • @mozzbozz I agree. The first answer is the best choice. This can be a second alternate option. Edited the answer according to your suggestion. Thanks! – Sjs Aug 21 '17 at 14:35
  • 2
    If you want to trigger the option, I think iface.actionZoomToSelected().trigger() is a little safer :) – Joseph Aug 21 '17 at 14:35
  • @Joseph can u pls edit the answer according to your suggestion? – Sjs Aug 21 '17 at 14:38
  • 1
    @Joseph I wouldn't mind that ;) happy that you made the answer look even better ! – Sjs Aug 21 '17 at 14:45
0

# The first a QMessageBox display all selected features:

lyr = iface.activeLayer();
fts = lyr.selectedFeatures();
ftsCount = lyr.selectedFeatureCount();
sFts = str(ftsCount);
msgBox = QMessageBox();
msgBox.setText(sFts +' selected features');
msgBox.exec_();

# Second zoom to selected features:

iface.actionZoomToSelected().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.