Search code examples
pythonpyqtpyqt4qgis

How to select and zoom to a layer in QGIS using Python


I am using QGIS 2.8.1, and I want to select the shapefile called 'tempshpfile' and zoom to layer on that polygon shapefile.

My code is:

import ogr,os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
import qgis.utils
import glob
import processing
from processing.core.Processing import Processing
from PyQt4.QtCore import QTimer

Processing.initialize()
Processing.updateAlgsList()

# Add array of address below

allFiles = ["C:/Shapefiles/Map_0077421.shp"]
filesLen = len(allFiles)

TexLayer = "C:/Texas_NAD27/Texas_NAD27.shp"

for lop in range(filesLen):
    wb = QgsVectorLayer(allFiles[lop], 'tempshpfile', 'ogr')
    wbTex = QgsVectorLayer(TexLayer, 'TexasGrid', 'ogr')
    QgsMapLayerRegistry.instance().addMapLayer(wb)
    QgsMapLayerRegistry.instance().addMapLayer(wbTex)

Solution

  • Since your wb layer is already registered just activate the layer after the loop:

    qgis.utils.iface.setActiveLayer(wb)
    

    And zoom to the extent of the active layer:

    qgis.utils.iface.zoomToActiveLayer()