I am new to pyqgis plugins with QT, I am writing code to replace multiple headers in the attribute field of a layer. I keep getting an error saying
'int' object has no attribute 'pendingFields'
What can I do?
Here is my code. The code accepts the current shapefile and renames the headers:
def run(self):
"""Run method that performs all the real work"""
# show the dialog
#This activates the layer on the table of content
self.dlg.layercombo.clear()
layers = self.iface.legendInterface().layers()
layer_list = []
for layer in layers:
layerType = layer.type()
if layerType == QgsMapLayer.VectorLayer:
layer_list.append(layer.name())
self.dlg.layercombo.addItems(layer_list)
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
# Do something useful here - delete the line containing pass and
# substitute with your code.
self.selectedlayerIndex = self.dlg.layercombo.currentIndex()
for field in self.selectedlayerIndex.pendingFields():
if field.name() == 'CC':
with edit(self.selectedlayerIndex):
idx = self.selectedlayerIndex.fieldNameIndex(field.name())
self.selectedlayerIndex.renameAttribute(idx, 'DD')
if field.name() == 'AA':
with edit(self.selectedlayerIndex):
idx = self.selectedlayerIndex.fieldNameIndex(field.name())
self.selectedlayerIndex.renameAttribute(idx, 'BB')
1 Answer 1
As @Hugo Roussaffa mentioned, an integer index is being returned to you which you are using to access the fields.
One method use is to instead get the current text of the combobox and then identify the QgsVectorLayer
which matches this name. You can then use this to access the fields and rename them as necessary:
if result:
self.selectedLayerName = self.dlg.layercombo.currentText()
self.selectedLayer = QgsMapLayerRegistry.instance().mapLayersByName(self.selectedLayerName)[0]
for field in self.selectedLayer.pendingFields():
if field.name() == 'CC':
with edit(self.selectedLayer):
idx = self.selectedLayer.fieldNameIndex(field.name())
self.selectedLayer.renameAttribute(idx, 'DD')
if field.name() == 'AA':
with edit(self.selectedLayer):
idx = self.selectedLayer.fieldNameIndex(field.name())
self.selectedLayer.renameAttribute(idx, 'BB')
-
@Stringz - Most welcome, glad it helped :)Joseph– Joseph2017年10月10日 09:13:02 +00:00Commented Oct 10, 2017 at 9:13
self.dlg.layercombo.currentIndex()
return an integer (the index of a layer in your combo), and not the layer itself, and the pendingFields method works on Layer Object.