17

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.

3 Answers 3

26

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()
0
10

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()
0
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();
1
  • Python does not require ;
    – Taras
    May 17 at 4:59

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.