1

I want to add new column to attribute table of vector layer via Python console. I'm trying to do this following instructions from http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html. But while defying caps

caps = layer.dataProvider().capabilities()

I'm getting error:

AttributeError: 'NoneType' object has no attribute 'dataProvider'

I've found some solutions referring to setting up QGIS Python environment correctly. (Getting dataProvider from vector layer outside QGIS). But this solution crash my QGIS.

Any idea what should I do to access (?) (or rather 'get?') dataProvider?

  • 1
    Welcome to GIS:SE @antonio! How did you define your layer and which QGIS version are you using? – Joseph Feb 23 '16 at 10:31
  • As for now I want to add the column to active layer in project, so: layer = qgis.utils.iface.activeLayer() QGIS version: 2.12 – antonio Feb 23 '16 at 10:46
  • Are you wanting to add a new column inside QGIS or outside? – Joseph Feb 23 '16 at 10:54
  • Inside. (But I'm not sure if I understand this question corectly.) I want to add the column to existing attribute table of activeLayer. Like via GUI: open attribute table -> start editing -> add new column -> set name, type, etc. -> done – antonio Feb 23 '16 at 10:58
2

You could use the following to add a new field and determining its type:

from PyQt4.QtCore import *

layer = qgis.utils.iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes( [ QgsField("Name", QVariant.String) ] )
layer.commitChanges()
  • 1
    Thanks a lot! It works perfectly and does exactly what I need. – antonio Feb 23 '16 at 11:18
  • @antonio - Awesome buddy! Glad it works :) – Joseph Feb 23 '16 at 11:21

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.