获取QGIS 2.x python代码以在QGIS 3.x中工作?对象没有属性“ legendInterface”的问题


12

下面的代码在QGIS 2.x中运行良好,但是在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())

这是我运行代码时遇到的错误:

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'

有人知道新版本中替换了'legendInterface'的内容还是要使其在QGIS 3.0中运行可能需要做哪些其他更改?

Answers:


14

您可以替换为:

layers = iface.legendInterface().layers()

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

该解决方案对我来说效果不佳,因为获得的图层的顺序与“图层面板”中列出的顺序不同。
AleksMat

@AleksMat-很高兴知道您找到了解决问题的方法:)
Joseph

9

相当于

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

在QGIS 3.0中

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

这将以递归方式查找所有图层,并以“图层面板”中列出的相同顺序返回它们。


3

我发现这列出了层:

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


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.