3

I am trying to create a list-type field for the active layer using the code below, which is not working.

Is there any other way to create a list-type field and update the list([1,2,3]) as an attribute value to the created area?

layer = iface.activeLayer()

field = 'list_field'
if layer.fields().indexFromName(field) == -1:
    fieldz = QgsField(field , QVariant.list)
    layer.dataProvider().addAttributes([fieldz])
    layer.updateFields()

enter image description here

1 Answer 1

3

I could get the same error as you:

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 5, in <module>
AttributeError: type object 'QVariant' has no attribute 'list'

This happened due to the wrong specification of the QVariant type. It should be QVariant.List instead of QVariant.list, see the documentation:

from qgis.core import QgsField, QgsVariantUtils
from PyQt5.QtCore import QVariant

new_field = QgsField("ListField", QVariant.List)
print(QgsVariantUtils.typeToDisplayString(new_field.type())) # List

So, your code can be adjusted as follows:

from qgis.gui import QgisInterface
from qgis.core import QgsField
from PyQt5.QtCore import QVariant

layer = iface.activeLayer()

field = 'list_field'
if layer.fields().indexFromName(field) == -1:
    fieldz = QgsField(field , QVariant.List)
    layer.dataProvider().addAttributes([fieldz])
    layer.updateFields()

However, I would probably proceed in a slightly different manner to create a new field:

from qgis.gui import QgisInterface
from qgis.core import QgsField
from PyQt5.QtCore import QVariant

layer = iface.activeLayer()

field = 'list_field'

if field not in layer.fields().names():
    layer_provider = layer.dataProvider()
    layer_provider.addAttributes([QgsField(field, QVariant.List)])
    layer.updateFields()

Also, keep in mind that you may encounter the following error e.g.:

Layer <LAYER_NAME>: type for field list_field not found

References:

Your Answer

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

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