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!