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 (<class 'qgis._core.QgsLayerTreeGroup'>)
- Aerial Photos (<class 'qgis._core.QgsLayerTreeGroup'>)
- Other Maps (<class 'qgis._core.QgsLayerTreeGroup'>)
- Model Results (<class 'qgis._core.QgsLayerTreeGroup'>)
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()
[<qgis._core.QgsLayerTreeGroup object at 0xa3f9170>, <qgis._core.QgsLayerTreeGroup object at 0xa3f9200>, <qgis._core.QgsLayerTreeGroup object at 0xa3f9290>, <qgis._core.QgsLayerTreeGroup object at 0xa3f9320>, <qgis._core.QgsLayerTreeLayer object at 0xa3fe320>, <qgis._core.QgsLayerTreeLayer object at 0xa3fe830>]
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.