5

I'm trying to use pyqgis to retrieve the name of the group in which a layer with a specified name is located. My function code is as follows:

def runA4(self,inputRasterName,outputFilename,outputLayerName):
    root = QgsProject.instance().layerTreeRoot()
    print "root:"
    print root

    demRaster = root.findLayer(inputRasterName)
    print "demRaster:"
    print demRaster

    parentGroup = demRaster.parent()
    print "parentGroup:"
    print parentGroup

This gives the following output in the Python console:

root:
<qgis._core.QgsLayerTreeGroup object at 0x0000000025287730>
demRaster:
None

And the following in the "Python error" log messages panel:

2017-10-17T16:42:40 1   Traceback (most recent call last):
    File "C:/Users/Gareth/.qgis2/python/plugins\myPlugin\myPlugin.py", line 1749, in runA4D
        self.runA4(inputRasterName,outputFilename,outputLayerName)
    File "C:/Users/Gareth/.qgis2/python/plugins\myPlugin\myPlugin.py", line 1761, in runA4
        parentGroup = demRaster.parent()
    AttributeError: 'NoneType' object has no attribute 'parent'

So there's something going wrong when I try to grab demRaster using inputRasterName, which is a string containing the name of the layer as listed in the layer tree. What am I doing wrong here?

I can't help but think there must be a better way to do this - it seems like it should be a very simple operation!

2 Answers 2

4

As the documentation says, the findLayer() method need a layer Id (https://qgis.org/api/classQgsLayerTreeGroup.html) and not the layer name.

You can get the layer Id from the name this way:

QgsMapLayerRegistry.instance().mapLayersByName('layerName')[0].id()

So your function must be something like this :

def runA4(self,inputRasterName,outputFilename,outputLayerName):
    root = QgsProject.instance().layerTreeRoot()
    print "root:"
    print root

    demRaster = root.findLayer(QgsMapLayerRegistry.instance().mapLayersByName(inputRasterName)[0].id())
    print "demRaster:"
    print demRaster

    parentGroup = demRaster.parent()
    print "parentGroup:"
    print parentGroup

You can also check if everything is right by some print statement with the name() method that is callable on every objects of the QgsLayerTreeRoot.

4

you can create a simple function for obtain the parent group name,for example:

from qgis.core import *

_layerreg = QgsMapLayerRegistry.instance()

def LayerParentGroupFromName(name):
    root = QgsProject.instance().layerTreeRoot()
    layers = QgsMapLayerRegistry.instance().mapLayersByName(name)
    for layer in layers:
        root_layer = root.findLayer(layer.id())
        if root_layer:
            print root_layer.parent().name ()

And for usage:

LayerParentGroupFromName("airports")

enter image description here

Your Answer

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

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