PyQGIS v3 – Adding Attribute with PyQGIS v3

pyqgis-3pythonqgis

I'm currently updating a plugin that I wrote a long time ago for Qgis v2. I have a line that add attributes to a vector layer written as below but it's getting an error:

provider.addAttributes([ QgsField(att, QVariant.Int) ])
NameError: name 'QVariant' is not defined

I have looked in the Python documentation for PyQgis v3 for add attribute and found this:
https://qgis.org/pyqgis/master/core/Vector/QgsVectorDataProvider.html?highlight=addattributes#qgis.core.QgsVectorDataProvider.addAttributes
But I don't understand what I need to pass to this function to make it work properly.

Best Answer

You may need to import it from your plugin using:

from PyQt5.QtCore import QVariant

The method you are using should be correct, don't forget to update the attribute fields. The following is a simple working example:

vLayer = iface.activeLayer()    
vLayer.dataProvider().addAttributes([QgsField('ID', QVariant.Int)])
vLayer.updateFields()
Related Question