I selected the layer I want to zoom in and I can actually zoom in using the python console that Qgis provides using


but if I do the same in my code, is like that line is being ignored.

code here:

def openFileNameDialog(self):

    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Shapefile's (*.shp)", options=options)
    if fileName:
        shape_name = fileName

    shapelayer = QgsVectorLayer(fileName, "project's shapefile", "ogr")
    if not shapelayer:
      self.statusBar().showMessage('shapefile is invalid')


        urlWithParams = 'url.to.map'

        rlayer = QgsRasterLayer(urlWithParams, 'BaseMap', 'wms')

        if not rlayer.isValid():
            self.statusBar().showMessage('Layer failed to load!')



        #self.boxlayer = self.iface.activeLayer()
        #self.canvastry = self.iface.mapCanvas()
        #extent = self.boxlayer.extent()
        #self.box = self.boxlayer.boundingBoxOfSelected()


commented lines between setActiveLayer() and zoomToActiveLayer() are other tries i've done and haven't worked from what I've read in the forums.


I've realized that iface.zoomToActiveLayer() is working but it's also being called before layers are loaded into Qgis and that's the bug preventing that line to execute correctly.


calling the


is the correct method to use, so calling the line after the layers are loaded would solve the problem.

Using render signals it can be automatically zoomed in

| improve this answer | |

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.