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()
asked Jul 11, 2016 at 14:16
2 Answers 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
-
but not in pluginЕвгения Сидоренко– Евгения Сидоренко2016年07月13日 14:37:02 +00:00Commented 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.Fran Raga– Fran Raga2016年07月13日 14:46:10 +00:00Commented Jul 13, 2016 at 14:46
-
something wron in import block, mb?Евгения Сидоренко– Евгения Сидоренко2016年07月13日 14:48:13 +00:00Commented Jul 13, 2016 at 14:48
-
@Евгения Сидоренко, within the plugin are you importing QVariant, from PyQt4.QtCore import QVariantartwork21– artwork212017年05月11日 12:18:30 +00:00Commented May 11, 2017 at 12:18
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
lang-py
selectedLayer
variable, thenself.selectedLayer
. Those are note the same variables. Is this intended? This may be the cause of your issue.