[GIS] Getting bounding box of a selected region through PyQGIS

extentspyqgis

Assume I have selected several features of a layer in QGIS and I would like to get the bounding information of the whole selected area through python console like the bounding of yellow regions the figure shows.

What is the easiest method to do it?

enter image description here

p.s. I have tried to use layer.selectedFeatures() but it just extract the list of selected features but cannot directly get the bounding info.

Best Answer

this is simpel in pyqgis:

layer = iface.activeLayer() # is the currently selected layer
box = layer.boundingBoxOfSelected() # creates a bounding box
iface.mapCanvas().setExtent(box) # zooms to this bounding box

you could also scale the box variable with

box.scale(2,box.center()[0], box.center()[1])

where "2" is the scale factor.

Tested with QGIS 2.18. For further research have a look athe pyqgis api of boundingBoxOfSelected