2

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"
selectedLayer.dataProvider().addAttributes([QgsField(name,QVariant.Double)]) 
self.selectedLayer.updateFields()
#or
self.selectedLayer.commitChanges()
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jul 11, 2016 at 14:16
6
  • 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. Commented Jul 11, 2016 at 14:29
  • I have tried in different ways, do not get any! Commented Jul 11, 2016 at 14:41
  • Have you started editing by selectedLayer.startEditing()? Commented Jul 11, 2016 at 15:02
  • yes, i tried it Commented Jul 11, 2016 at 15:03
  • i think problem in this command selectedLayer.dataProvider().addAttributes([QgsField(name,QVariant.Double)]), becauce without it code goes down and work! Commented Jul 11, 2016 at 15:06

2 Answers 2

2

This example work perfectly.

from PyQt4.QtCore import *
lyr = iface.activeLayer()
lyr.startEditing()
provider = lyr.dataProvider()
provider.addAttributes([QgsField("newAttribute", QVariant.Double)])
lyr.updateFields()
lyr.commitChanges()
answered Jul 13, 2016 at 13:15
4
  • but not in plugin Commented Jul 13, 2016 at 14:37
  • why not?this code work in a plugin or in qgis console.You probably need check your plugin.If you need examples of addatributes etc..Check this class github.com/All4Gis/instagram2qgis/blob/master/… and the CreateShape method for example. Commented Jul 13, 2016 at 14:46
  • something wron in import block, mb? Commented Jul 13, 2016 at 14:48
  • @Евгения Сидоренко, within the plugin are you importing QVariant, from PyQt4.QtCore import QVariant Commented May 11, 2017 at 12:18
1

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) ] ) 
selectedLayer.updateFields()
answered Jul 25, 2016 at 12:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.