[GIS] AttributeError: ‘int’ object has no attribute ‘setName’ (or insertChildNode)

attributeerrorpyqgis

I am trying to make group and fill it with layers in pyQGIS.

Piece of my code:

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QFileInfo

from qgis.core import *
from qgis.utils import iface 

group = iface.legendInterface().addGroup( 'abc')
group.setName("Group X")

But I got only error AttributeError: 'int' object has no attribute 'setName'

May I import some other class or where is problem?

Best Answer

I suggest you to avoid the legendInterface and use instead Layer Tree classes directly.

You're getting that error because addGroup returns an index (integer), that you're storing in your group variable and then calling a method that integers don't support.

You can see how to add groups (and even subgroups) to QGIS Layer Tree here: How to add a layer group using pyQGIS?

Once you've added a group, you can add layers to it by calling addLayer():

myGroup.addLayer(myLayer)

Have a look at these related posts: