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

Taras
  • 32,823
  • 4
  • 66
  • 137
Ganesh S
  • 39
  • 2

1 Answers1

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:

Taras
  • 32,823
  • 4
  • 66
  • 137