Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
About the Author
About the Reviewers

Adding a field to a vector layer

This recipe demonstrates how to add a new field to a layer. Each field represents a new column in a dataset for which each feature has a new attribute. When you add a new attribute, all the features are set to NULL for that field index.

Getting ready

We will use the New York City museums' shapefile used in other recipes, which you can download as a ZIP file from

Extract this shapefile to /qgis_data/nyc.

How to do it...

All the data management for a layer is handled through the layer's data provider and the fields are no different. We will load the layer, access the data provider, define the new field, and finalize the change, as follows:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First, you must import the Qt library's data types, which PyQGIS uses to specify the layer field's data types:

    from PyQt4.QtCore import QVariant
  4. Next, load and validate the layer:

    vectorLyr =  QgsVectorLayer('...