Remember i am using Python Version 3.6.2 QGIS Version 3.2
while running my code i am getting this error:
fields = selectedLayer.pendingFields()
AttributeError: 'QgsRasterLayer' object has no attribute 'pendingFields
if i am using fields() instead of pendingFields() because of qgis version 3x
getting this error:
fields = selectedLayer.fields()
AttributeError: 'QgsRasterLayer' object has no attribute 'fields
i am new in this field so please tell me properly what should i do
here is my code:
filename = self.dlg.lineEdit.text()
output_file = open(filename, 'w')
selectedLayerIndex = self.dlg.comboBox.currentIndex()
selectedLayer = layers[selectedLayerIndex]
fields = selectedLayer.pendingFields()
fieldnames = [field.name() for field in fields]
for f in selectedLayer.getFeatures():
line = ','.join(unicode(f[x]) for x in fieldnames) + '\n'
unicode_line = line.encode('utf-8')
output_file.write(unicode_line)
output_file.close()
-
i just simply created a plugin it didn't ask for QgsRasterLayer or QgsVectorLayer. from qt creator i design my plugin to take the layers raster or vector from my local system and it save output file but when ever i am saving output file i am getting this errorRahul Verma– Rahul Verma2018年12月21日 00:35:26 +00:00Commented Dec 21, 2018 at 0:35
-
i am absolute beginners in QGIS so i am not getting it well what i want to do is ----- i created my plugin i just want to add some code in my mainPlugin.py file like print('hello') and want to run this in qgis so what should i do.Rahul Verma– Rahul Verma2018年12月21日 00:37:54 +00:00Commented Dec 21, 2018 at 0:37
1 Answer 1
Your code will not work with raster layers as they have neither fields (QGIS doesn't support raster attribute tables - link) nor features.
fields
(pendingFields
in 2x) and getFeatures
are methods of the QgsVectorLayer
class.
So test if your layer has a fields
method (i.e if hasattr(selectedLayer, 'fields'): etc...
and ignore it if it doesn't. i.e
filename = self.dlg.lineEdit.text()
selectedLayerIndex = self.dlg.comboBox.currentIndex()
selectedLayer = layers[selectedLayerIndex]
if hasattr(selectedLayer, 'fields'):
fields = selectedLayer.pendingFields()
fieldnames = [field.name() for field in fields]
for f in selectedLayer.getFeatures():
etc...
-
error gone but its not saving my output file. will you forgot to add output_file = open(filename, 'w') in second line. After adding it on 2nd line output file showing in my systemRahul Verma– Rahul Verma2018年12月21日 01:11:51 +00:00Commented Dec 21, 2018 at 1:11
-
The
etc...
in my code snippet represents the rest of your code, including the output. I didn't forget it, I deliberately didn't include it as it's not relevant to the question and to keep my answer simple.user2856– user28562023年01月20日 09:08:56 +00:00Commented Jan 20, 2023 at 9:08
Explore related questions
See similar questions with these tags.