Mittwoch, 31. Oktober 2012

Basics: Creating a new layer in QGIS with Python

You want to create a new layer out of python worries.

Just create a new layerobject like this:

 from qgis.core import QgsVectorLayer, QgsField, QgsMapLayerRegistry  
 from PyQt4.QtCore import QVariant  

 'create Layer'  
 self.lineLayer = QgsVectorLayer("LineString", name, "memory")   

LineString is the type of layer you want to create. (e.g. Point, LineString or Polygon)
name is obviously the displayed name of the layer.
memory is the storagetype. it is just an unsaved memorylayer in this example.

After that you need to specifiy the layerattributes. (if you want to)
To do that you have to get the dataprovider of the layer and set it to "editable" to add the attributes you want the included features to have. To commit your changes to the attributetable use the commitChanges()-Function of the QgsVectorLayer.

 'set Attributes' 
 self.layerData = self.lineLayer.dataProvider() 
 self.layerData.addAttributes([ QgsField("ID", QVariant.String), QgsField("latStart", QVariant.String), QgsField("lonStart", QVariant.String), QgsField("latEnd", QVariant.String), QgsField("lonEnd", QVariant.String) ])#

Now the fresh layer needs to be added to the MapLayerRegistry within QGIS so it is out there for the world to see.

 'show Layer in QGIS'  


1 Kommentar:

  1. How can I create a vector layer with attributes, that i had got from attrs = feature.attributes() function?