Saving a map to a project

Saving a project automatically can be useful for autosave features or as part of a process to autogenerate projects from dynamically updated data. In this recipe, we'll save a QGIS project to a .qgs project file.

Getting ready

You will need to download the following zipped shapefile and extract it to your qgis_data directory, to a subdirectory named ms:

https://geospatialpython.googlecode.com/svn/Mississippi.zip

How to do it...

We will create a simple QGIS project by loading a shapefile layer, then we'll access the project object, and save the map project to a file, as follows:

  1. First, we need the Qt core library in the QGIS Python console:
    from PyQt4.QtCore import *
    
  2. Next, we load the shapefile and add it to the map:
    lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
    reg = QgsMapLayerRegistry.instance()
    reg.addMapLayer(lyr)
    
  3. Then, we create a file object to save our project:
    f = QFileInfo("/Users/joellawhead/qgis_data/myProject.qgs")
    
  4. Now, we can access the QGIS project object instance:
    p = QgsProject.instance()
    
  5. Finally, we can save the project by writing it to the file object:
    p.write(f)
    

How it works...

QGIS simply creates and XML document with all the project settings and GIS map settings. You can read and even modify the XML output by hand.

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

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