5

What is the correct expression of "legendInterface()" in qgis3.0? I tried with "layerTreeNode", but it doesn't work.

root = QgsProject.instance().layerTreeRoot()

for group in [child for child in root.children() if child.nodeType() == 0]:
    if group=="POSTE_DETENTE":
        group_actif = root.findGroup(group)
        #now, I would iterate on layers in the list L in order to get the polygon layers
        for (type, sys, champ, name) in L:
          #get the polygon layer
          if type=='polygon':
            #create_layer is a function that I create previously and return a new layer in memory
            layer=create_layer(type, sys, champ, name):
            # add layer to the legend
            QgsProject.instance().addMapLayer(layer, False)
            # add layer to the group - False to let the choice where to place the layer in the group
            group_actif.addLayer(layer)

1 Answer 1

4

I think this is what you're looking for:

root = QgsProject.instance().layerTreeRoot()

for group in [child for child in root.children() if child.nodeType() == 0]:
    if group.name() == 'POSTE_DETENTE':
        …

Node types: NodeGroup - 0, NodeLayer - 1

Please also see help(QgsLayerTreeLayer) for additional reference

6
  • The error is in the second line: AttributeError: 'QgisInterface' object has no attribute 'layerTreeNode'
    – ennine
    May 18, 2018 at 17:09
  • 1
    Are you trying to get to the layer objects? layers = [tree_layer.layer() for tree_layer in QgsProject.instance().layerTreeRoot().findLayers()]
    – Basile
    May 18, 2018 at 17:21
  • I try to iterate on groups. The expression "iface.legendInterface().groups()" works perfectly in pyqgis2.0, but not the case in pyqgis3.0.
    – ennine
    May 18, 2018 at 19:14
  • Okay now I see. Please check an updated solution
    – Basile
    May 18, 2018 at 23:12
  • 1
    Many thanks Basile. In fact, I have to consider subchild in child.
    – ennine
    May 19, 2018 at 14:04

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.