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?


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
  • 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
  • 1
    Seems that setAttributeMap is no longer a method of QgsFeature classes, so this solution doesn't work for the most recent (its 2016) QGIS. – Spacedman Aug 8 '16 at 7:25

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, provider.crs() )
  • 1
    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 '15 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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