I'm trying to add a new attribute to a vector layer in my plugin. But it does not work.. Why?

selectedLayerIndex = self.dlg.comboBox.currentIndex()
selectedLayer = layers[selectedLayerIndex]
name = "newAttribute"
  • 1
    You are first using the selectedLayer variable, then self.selectedLayer. Those are note the same variables. Is this intended? This may be the cause of your issue. – ArMoraer Jul 11 '16 at 14:29
  • I have tried in different ways, do not get any! – Евгения Сидоренко Jul 11 '16 at 14:41
  • Have you started editing by selectedLayer.startEditing()? – okorkut Jul 11 '16 at 15:02
  • yes, i tried it – Евгения Сидоренко Jul 11 '16 at 15:03
  • i think problem in this command selectedLayer.dataProvider().addAttributes([QgsField(name,QVariant.Double)]), becauce without it code goes down and work! – Евгения Сидоренко Jul 11 '16 at 15:06

This example work perfectly.

from PyQt4.QtCore import *

lyr = iface.activeLayer()
provider = lyr.dataProvider()
provider.addAttributes([QgsField("newAttribute", QVariant.Double)])

I once had issues using the currentIndex() method (which might be unrelated to the issue you have). Instead, I use the currentText() method to identify the layer and add attribute fields:

from PyQt4.QtCore import QVariant

selectedLayerIndex = self.dlg.comboBox.currentText()
selectedLayer = QgsMapLayerRegistry.instance().mapLayersByName(selectedLayerIndex)[0]
name = "newAttribute"
selectedLayer.dataProvider().addAttributes( [ QgsField(name, QVariant.Double) ] )            

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.