Thursday, 2 March 2017

pyqgis - QGIS layer tree API returns only groups and not layers


I am trying to use the QGIS python API to read out the groups and layers in a QGIS (2.4) project. Here is a code snippet from my script, which is run from a shell, not from the QGIS python console!


from PyQt4.QtCore import QFileInfo
from qgis.core import *


proj=QgsProject.instance()
proj.read(QFileInfo("/var/qgis-projects/testproject.qgs"))

print "QGis version:"+QGis.QGIS_VERSION
print "Project title: "+proj.title()
print "Project tree root children:"
root=proj.layerTreeRoot()
for node in root.children():
print "- "+node.name()+" ("+str(type(node))+")"


It prints the following when I run it:


QGis version:2.4.0-Chugiak
Project title: This is my project title
Project tree root children:
- Field Data ()
- Aerial Photos ()
- Other Maps ()
- Model Results ()


Only QgsLayerTreeGroup objects are returned but no layers (QgsLayerTreeLayer objects), even though I also have two layers in the project root. When I open the python console in QGIS while I have my project open and run:


QgsProject.instance().layerTreeRoot().children()
[, , , , , ]

This does return the QgsLayerTreeLayer objects for my layers that I'm after. How come there is a difference?


Edit: I'm trying to run my python script from a shell, not from the QGIS python console.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...