14

The following piece of code works well in QGIS 2, however, it does not work in QGIS 3.

myDir = 'd:/work/output_folder/'

layers = iface.legendInterface().layers()
pipe = QgsRasterPipe()

for layer in layers:
   extent = layer.extent()
   width, height = layer.width(), layer.height()
   renderer = layer.renderer()
   provider = layer.dataProvider()
   crs = layer.crs().toWkt() 
   pipe.set(provider.clone())
   pipe.set(renderer.clone())
   opts = ["COMPRESS=LZW"] 
   file_writer = QgsRasterFileWriter(myDir + layer.name() + ".tif")
   file_writer.setCreateOptions(opts)
   file_writer.writeRaster(pipe, width, height, extent, layer.crs())

This is the error I get when I run the code:

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.0\apps\Python36\lib\code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
AttributeError: 'QgisInterface' object has no attribute 'legendInterface'

Does someone know what has replaced legendInterface in the new version or what other changes I might have to make to get this to run in QGIS 3?

4 Answers 4

21

You could just replace

layers = iface.legendInterface().layers()

with

layers = [layer for layer in QgsProject.instance().mapLayers().values()]
2
  • This solution did not work well enough for me as the obtained layers were not in the same order as listed in Layers Panel.
    – AleksMat
    Commented Apr 19, 2018 at 8:57
  • @AleksMat - Good to know that you found a method for your problem :)
    – Joseph
    Commented Apr 20, 2018 at 9:13
11

The equivalent of

layers = self.iface.legendInterface().layers()

in QGIS 3 is

layers = [tree_layer.layer() for tree_layer in QgsProject.instance().layerTreeRoot().findLayers()]

This recursively finds all layers and returns them in the same order as listed in Layers Panel.

4

I found this to list layers:

layers = qgis.core.QgsProject.instance().layerTreeRoot().layerOrder()
4

Have a look at https://qgis.org/api/api_break.html - there are literally thousands of changes to the API, which scripts need to be upgraded to handle.

QgsLegendInterface was removed. It was replaced by layer tree API (QgsLayerTreeNode class and others). Methods that deal with custom actions in main window's layer tree context menu were moved to QgisInterface:

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.