When I try to add a field programmatically with the following code:

import os.path
from PyQt4 import QtGui, QtCore
legend = qgis.utils.iface.legendInterface()
allLayers = legend.layers()
for i in allLayers:
  lyrName = i.name()
  GDBname = str(lyrName)
  print GDBname.split('_', 1)[0]
  lyrProv = i.dataProvider()
  lyrProv.addAttributes( [ QgsField("testName", QVariant.double) ] )

I receive an error:

lyrProv.addAttributes( [ QgsField("testName", QVariant.double) ] ) NameError: name 'QVariant' is not defined

Can someone help?

  • 9
    Just figured it out. I had to change the import statement to: from PyQt4.QtCore import * – Jon Gottsegen May 13 '14 at 18:58
  • 4
    This question and answer solves the problem of adding attributes as per the pyQGIS cookbook and failing to add "from PyQt4.QtCore import *" which is NOT specified on that page (or anywhere else that I could find). In that respect this Q/A is very useful. – Mr Purple Mar 1 '15 at 20:46
  • I had exactly this issue using QGIS 2.01 on Ubuntu. Same solution also, though I would have preferred not to have to resort to import all. – AnserGIS Aug 12 '16 at 13:34
  • Worth noting that a standalone process in QGIS3.X should include the line from PyQt4.QtCore import * to solve the problem – Mr Purple Jun 23 '19 at 0:33

Browse other questions tagged or ask your own question.