Sign up ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am new to python and QGIS. I have looked at a few tutorials of python scripts for QGIS. All of them create new vector and raster layers with some existing data source. eg. shapefile or geotiff or postgis database table.

Is it possible to create a QGIS layer through a python script, where i can create/add/modify new features through the python script, as the need arises. It will be typically a vector layer with point data and custom symbols.

Will this be possible? Is there a example i can look at?

share|improve this question

2 Answers 2

up vote 12 down vote accepted

Have a look at the Memory provider as described in PyQGIS Cookbook.

Memory provider is intended to be used mainly by plugin or 3rd party app developers. It does not store data on disk, allowing developers to use it as a fast backend for some temporary layers.

# To avoid 'QVariant' is not defined error
from PyQt4.QtCore import *

# create layer
vl = QgsVectorLayer("Point", "temporary_points", "memory")
pr = vl.dataProvider()

# Enter editing mode

# add fields
pr.addAttributes( [ QgsField("name", QVariant.String),
                QgsField("age",  QVariant.Int),
                QgsField("size", QVariant.Double) ] )

# add a feature
fet = QgsFeature()
fet.setGeometry( QgsGeometry.fromPoint(QgsPoint(10,10)) )
fet.setAttributeMap( { 0 : QVariant("Johny"),
                   1 : QVariant(20),
                   2 : QVariant(0.3) } )
pr.addFeatures( [ fet ] )

# Commit changes
share|improve this answer
Thank you for the reply, it was certainly helpful. However when using the the script i get the following error. "NameError: name 'QVariant' is not defined" I left the "addAttributes" part out and managed to put a dot on the map, so it works, thank you. I am using Ubuntu 12.04 and QGIS 1.8.0-Lisboa But what can cause the above mentioned error? – Theuns Heydenrych Jul 26 '12 at 7:54

If you want to save a new vector layer (.shp) in your Hard Disk you have to use QgsVectorFileWriter(). It takes several parameters, the simplest way is to use the parameters from the project you are using. Have a look to this site.

   cLayer = qgis.utils.iface.mapCanvas().currentLayer()
   provider = cLayer.dataProvider()
   writer = QgsVectorFileWriter( "output_path_and_name.shp", provider.encoding(), provider.fields(),QGis.WKBPolygon, )
share|improve this answer
But this is creating the empty .shpfile.If i want to save the existing shapefile to specified path how can i do that? – user99 Jan 12 at 10:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.