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


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
  • Ah! you add the attributes to the provider not the layer, that's what I had confused. I miscopied the example and no amount of staring at the code helped. Clearly layer also has a addAttributes method! – Russell Fulton Jul 24 '17 at 2:16

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.