12

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

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.0?

16

You could just replace:

layers = iface.legendInterface().layers()

with

layers = [layer for layer in QgsProject.instance().mapLayers().values()]
| improve this answer | |
  • 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 Apr 19 '18 at 8:57
  • @AleksMat - Good to know that you found a method for your problem :) – Joseph Apr 20 '18 at 9:13
9

The equivalent of

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

in QGIS 3.0 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.

| improve this answer | |
3

I found this to list layers:

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

| improve this answer | |
2

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

| improve this answer | |

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.