I am new to Python and QGIS. I want to populate the comboBox with the first column of the table attribute of the park's layer
Code:
#Populate park's comboBox
park = layers[0].layer()
park.startEditing()
for p in park.getFeatures():
self.dlg.comboBox_2.addItem(p.attributes()[0])
Error:
2022年01月03日T01:39:23 WARNING Traceback (most recent call last):
File "C:/Users/ADS/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\urban_parks\urban_parks.py", line 217, in run
self.dlg.comboBox_2.addItem(p.attributes()[0]) TypeError: arguments did not match any overloaded call: addItem(self, str, userData: Any = None): argument 1 has unexpected type 'int'
addItem(self, QIcon, str, userData: Any = None): argument 1 has unexpected type 'int'
1 Answer 1
The problem is that the feature attributes which you are trying to add to your combo box are evidently of an integer datatype. The addItem()
method of QComboBox
expects a string argument.
Therefore, you need to cast the attribute value argument to a string:
...
for p in park.getFeatures():
self.dlg.comboBox_2.addItem(str(p.attributes()[0]))
...
-
2You will also need to remember that when you fetch the selected value from the combo box, it will be returned as a string. To be consistent with the type in the attribute, you will want to convert it back to an int using the
int()
function.Llaves– Llaves2022年01月03日 03:39:10 +00:00Commented Jan 3, 2022 at 3:39
startEditing
. In fact, you probably should avoid it.