1

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

iface.zoomToActiveLayer()

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')

    else:

        urlWithParams = 'url.to.map'

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

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

        QgsProject.instance().addMapLayer(rlayer)
        QgsProject.instance().addMapLayer(shapelayer)

        self.iface.setActiveLayer(shapelayer)

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

        self.iface.zoomToActiveLayer()

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

EDIT:

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.

0

calling the

iface.zoomToActiveLayer()

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

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.