When I run the following in a plugin I get

name 'QgsLayerTreeLayer' is not defined

print('Loading raster layer...')
print("%s called %s" % (filePath, fname))
tLayer = QgsRasterLayer(filePath, fname, 'gdal')
QgsProject.instance().addMapLayer(tLayer, False)
layerTree = iface.layerTreeCanvasBridge().rootGroup()
layerTree.insertChildNode(-1, QgsLayerTreeLayer(tLayer))

However in python console it works

tLayer = QgsRasterLayer(filePath, 'imagery', 'gdal')
layerTree.insertChildNode(-1, QgsLayerTreeLayer(tLayer))

Note: When I try the plugin without layerTree = iface.layerTreeCanvasBridge().rootGroup() I get

name 'layerTree' is not defined

The plugin imports

from qgis.core import QgsApplication, QgsVectorLayer, QgsRasterLayer, QgsProject 
from qgis.utils import iface

Should I import something else? This is based on https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html

Purpose is to get the raster to load under all layers and also to stay on the bottom if other vectors are loaded after it.

  • 1
    Have you tried just adding the QgsLayerTreeLayer class to your import statement? – Ben W Mar 2 '19 at 0:31
  • No I didn't but that worked...please post as the answer to accept. – GeorgeC Mar 2 '19 at 7:28

You need to import the QgsLayerTreeLayer class. Just add it to your import statement:

from qgis.core import QgsLayerTreeLayer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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