1

Followings is my code. I use it in QGIS 3.8.2. It shows "Expected an indented block" error. Please help me to sort the error out.

from PyQt5.QtCore import QVariant
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    if layer.name() == "Tree": 
with edit(layer):
        layer.dataProvider().addAttributes( [ QgsField("Name", QVariant.String, ",", 255) ] )
        layer.dataProvider().addAttributes( [ QgsField("Height", QVariant.String, ",", 255) ] )

else:
    pass

1 Answer 1

2

Python uses indentation to denote blocks of code, for example inside loops or if conditions, and also with. Basically whenever there's a : at the end of a line. So this should work:

from PyQt5.QtCore import QVariant
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    if layer.name() == "Tree": 
      with edit(layer):
        layer.dataProvider().addAttributes( [ QgsField("Name", QVariant.String, ",", 255) ] )
        layer.dataProvider().addAttributes( [ QgsField("Height", QVariant.String, ",", 255) ] )

    else:
      pass

Although you should probably indent it consistently, with maybe four spaces per block.

2
  • Thank you very much for your quick answer. :) Now i am facing the following error. Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 2, in <module> NameError: name 'QgsMapLayerRegistry' is not defined May 27, 2020 at 12:41
  • New error, new question please. Try and fix it yourself first though.
    – Spacedman
    May 27, 2020 at 13:00

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