Loading a map from a project

This recipe demonstrates how to load a project from a .qgs XML file. Loading a project will set up the map and project settings for a previously saved project within QGIS.

Getting ready

You will need to complete the previous recipe, Saving a map to a project, so that you have a project named myProject.qgs in your qgis_data folder.

How to do it...

For this recipe, you need to set up a file object, set a resource path, and then read the file object that references the project file. To do this, you need to perform the following steps:

  1. First, we import the core Qt library for the file object:
    from PyQt4.QtCore import *
    
  2. Next, we initiate the file object with the path to the project file:
    f = QFileInfo("/Users/joellawhead/qgis_data/myProject.qgs")
    
  3. Now, we access the project object:
    p = QgsProject.instance()
    
  4. Then, we set the resource path for QGIS to find data and other files, in case the project was saved with relative paths instead of absolute paths:
    p.readPath("/Users/joellawhead/qgis_data/")
    
  5. Finally, we tell the project object to read the project file in order to load the map:
    p.read(f)
    

How it works...

QGIS has a setting to save references to data and other files either as relative paths, which are relative to the project file, or absolute paths, which contain the full path. If the saved paths are absolute, PyQGIS will be unable to locate data sources. Setting the read path to the full system path of the project file ensures that QGIS can find all the referenced files in the project file, if they are saved as relative paths.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset