PyQGIS Vector Layer – Creating New Empty Vector Layer with PyQGIS

pyqgisqgis

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?

Best Answer

This does not work any longer in qgis3. See a slightly modified answer below.


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
vl.startEditing()
# 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
vl.commitChanges()