Each QGIS feature has two parts, the geometry and the attributes. In this recipe, we'll add an attribute for a layer from an existing dataset.
We will use a point shapefile with museum data for New York City, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Extract this shapefile to the /qgis_data/nyc
directory.
A feature must have geometry, but it does not require attributes. So, we will create a new feature, add some attributes, and then add everything to the layer, as follows:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
vpr = vectorLyr.dataProvider()
pnt = QgsGeometry.fromPoint(QgsPoint(-74.13401,40.62148))
fields
object for the layer that we'll need to create a new feature for:fields = vpr.fields()
f = QgsFeature(fields)
f.setGeometry(pnt)
f['NAME'] = 'Python Museum'
vpr.addFeatures([f]) vectorLyr.updateExtents()
PyQGIS attributes are defined as an ordered array
. The syntax for referencing a field is similar to the syntax for a Python dictionary. We use the layer's data provider object to perform the actual editing. When we use this approach, no signals are triggered at the layer object level. If we are just trying to edit data on the filesystem, that's okay, but if the layer is going to be added to the map canvas for display or user interaction, then you should use the editing buffer in the QgsVectorLayer
object. This editing buffer allows you to commit or roll back changes and also keeps track of the state of the layer when things are changed.