Wednesday 3 April 2019

pyqgis - Getting QGIS 2.x python code to work in QGIS 3.x? object has no attribute 'legendInterface' problem


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 "", line 1, in
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?




Answer



You could just replace:


layers = iface.legendInterface().layers()

with


layers = [layer for layer in QgsProject.instance().mapLayers().values()]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...