[GIS] Adding attributes to a new layer in pyqgis

fields-attributespyqgis

I am trying to create a temporary layer in a script but I can't get the attributes defined:

# create layer
    vl = QgsVectorLayer("Points", name, "memory")
    vl.addAttribute(QgsField('name', 10))

    print [f.name() for f in vl.pendingFields()]

prints []

Clearly I am missing something

I am working off code from replacement-of-qvariant-and-setattributemap-in-pyqgis

Best Answer

You are missing a couple important lines of code and the syntax is slightly off, try:

vl = QgsVectorLayer("Point", name, "memory") # removed "s" on Points
pr = vl.dataProvider() # need to create a data provider
pr.addAttributes([QgsField("name",  QVariant.Int)]) # define/add field data type
vl.updateFields() # tell the vector layer to fetch changes from the provider
Related Question