I'm writing a plugin that has a form with a combo box that I fill with the unique values in a field of a vector layer in the project.

The problem is that there are NULL values in that column and I get this error when I run the code:

TypeError: index 0 has type 'QVariant' but 'str' is expected

I'm trying with this code, but I still get the same error:

layer = QgsProject.instance().mapLayersByName('MyLayer')[0]
fieldsLayer = layer.fields()
idxField = fieldsLayer.indexFromName('MyField')
unique_values = layer.uniqueValues(idxField)

combovalues = []

for value in unique_values:
    if value == 'NULL':


1 Answer 1


'NULL' is not different from any string. Instead, you should use NULL. Remove apostrophes. NULL is automatically imported in QGIS. Outside QGIS you need to import NULL. It is a PyQGIS variant, not Python.

from qgis.core import NULL


for value in unique_values:
    if value == NULL:

  • I tried that, but then I get this error: NameError: name 'NULL' is not defined Commented Nov 11, 2020 at 19:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.