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.


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)])

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.