3

Using PyQGIS with QGIS 3, I am trying to zoom in a specific layer but I have not succeeded. He tried several answers but it doesn't work for me. Either it gives me a mistake or it does nothing to me

This is my code:

from qgis.utils import *
from qgis.PyQt.QtCore import *
from qgis.PyQt import QtGui
import os

fn8=rutas[2]
fn8=fn8.rstrip()
fn8=fn8+"\Datos Puntos Qgis.shp"
fn8=fn8.rstrip()

layer6 = QgsVectorLayer(fn8, 'ObrasCiviles', 'ogr')

QgsProject.instance().addMapLayer(layer6)#Lo añado al mapa de capas
QgsProject.instance().layerTreeRoot().findLayer(layer6.id()).setExpanded(False)

layer6 = iface.activeLayer ()

canvas = iface.mapCanvas ()
canvas = qgis.utils.iface.mapCanvas ()
canvas.zoomToSelected (layer6)
canvas.refresh ()

example

2
  • It is possible that your issues are in your paths. You should use Unix nomenclature without any space. This is recommended path for your code: "/Datos_Puntos_Qgis.shp". Fix whatever similar situation in it.
    – xunilk
    Nov 3, 2019 at 16:27
  • Thank you very much but the route works perfect. The only thing that does not generate is the zoom Nov 3, 2019 at 17:08

1 Answer 1

1

I don't see you actually selecting any data within the layer. If selection isn't important to you, could try something like:

canvas = iface.mapCanvas()
layer6.selectAll()
canvas.zoomToSelected()
layer6.removeSelection()
canvas.refresh()

Otherwise you could get the layer extents and then zoom to the bounding box:


canvas = iface.mapCanvas()
extent = layer6.extent()
canvas.setExtent(extent)
canvas.refresh()

You are right. I also tried but nothing happensenter image description here

1
  • Thanks for your help. I tried canvas = qgis.utils.iface.mapCanvas() #layer6.selectAll() #canvas.zoomToSelected() #layer6.removeSelection() extent = layer6.extent() #canvas = qgis.utils.iface.mapCanvas() canvas.setExtent(extent) #canvas = iface.mapCanvas() ##canvas.zoomToSelected(layer6).trigger() canvas.refresh() Nov 6, 2019 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.