I'm trying to load an existing .qgs project and get a list of the layers inside. I seem to be able to open the project, but I can't get the list of layers. I'm a little confused as to the basic PyQGIS syntax, and the cookbook doesn't cover this specific example.
from qgis.core import *
from PyQt4.QtCore import QFileInfo
QgsApplication.setPrefixPath(r"C:\OSGeo4W\apps\qgis-ltr", True)
qgs = QgsApplication([], False)
qgs.initQgis()
# Get the project instance
project = QgsProject.instance()
# Open the project
project.read(QFileInfo(
r'C:\path\to\project\project.qgs'))
print project.fileName()
# Get the layers in the project
layers = QgsMapLayerRegistry.instance().mapLayers()
print layers
qgs.exitQgis()
Currently, this just layers
returns an empty dict, despite the fact that the project exists and has many layers in it.
Best Answer
I also receive an empty dictionary when I run your code but the following works for me which is slightly different:
Tested on QGIS 2.18.3 for Windows 7 64-bit.
Edit:
The main difference, I believe, between your code and what I used is that you need to create the QApplication object before creating the QgsApplication. So you would need to replace:
with this:
But the QApplication class needs to be imported so we must add the following:
And finally, if you want to do a cleanup, you need to add the following at the end.
So you could try using the following code which is more close to your original code: