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.

Taras
  • 32,823
  • 4
  • 66
  • 137
Martin
  • 2,908
  • 4
  • 22
  • 44

3 Answers3

27

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()
Taras
  • 32,823
  • 4
  • 66
  • 137
Nathan W
  • 34,706
  • 5
  • 97
  • 148
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()
Taras
  • 32,823
  • 4
  • 66
  • 137
Sjs
  • 997
  • 1
  • 11
  • 23
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();
JGH
  • 41,794
  • 3
  • 43
  • 89
user107473
  • 21
  • 1