I've created a simple python script to load and show two layers and zoom to the first one. It looks like the script doesn't run the last 4 lines after I uncomment'print lyr1'. Anyway the map canvas is not changing.

from PyQt4.QtCore import *
from PyQt4.QtGui import *

canvas = iface.mapCanvas()

lyr1= QgsVectorLayer("C:\\Area1.shp", "Layer 1", "ogr")
lyr2= QgsVectorLayer("C:\\Area2.shp", "Layer 2", "ogr")
reg = QgsMapLayerRegistry.instance()
reg.addMapLayers([lyr1, lyr2])

#print lyr1

rect = QgsRectangle(lyr1.extent())
  • Your script works fine for me when running it in the python console and as a script. Where are you running it from? Try commenting out rect.scale(5) as that zooms the canvas out quite a bit. And are you wanting your script to show the layers (i.e. turn their visibility on)? – Joseph May 27 '16 at 9:30
  • I run the script from the python console within Qgis. Uncommenting rect.scale(5) offers no solution. Yes I want to see all the layers. – Steven May 27 '16 at 9:52
  • After the reg.addMapLayers([lyr1, lyr2]) line, use something like for layer in [lyr1, lyr2]: then indent next line and use iface.legendInterface().setLayerVisible(layer, True). This should check the loaded layers. – Joseph May 27 '16 at 10:00
  • Nope still the same. Both layers are visible, also without setLayerVisible. That's not the problem. There is also no problem if there is allready a layer in the legend/map. – Steven May 27 '16 at 10:22
  • Yes, I forgot there's a default setting in QGIS which shows loaded layers automatically so you're right, no need for the loop. Are you sure the last 4 lines are not being run? Did you test this by using print rect or print canvas at the end and see if it prints? – Joseph May 27 '16 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.