gpt4 book ai didi

python - 属性错误: 'QgsComposition' object has no attribute 'setMapCanvas'

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:36 25 4
gpt4 key购买 nike

我正在尝试使用 QGis map 编辑器保存 map 及其图例。我已经有了模板。

这是Python代码。

layers =iface.legendInterface().layers()
canvas=iface.mapCanvas()

for layer in layers:
# myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
newcomp = iface.createNewComposer()
newcomp.composition().loadFromTemplate(myDocument)
newcomp.composition().refreshItems()
for a in iface.mapCanvas().layers():
iface.legendInterface().setLayerVisible(a, False)
iface.legendInterface().setLayerVisible(layer, True)
newcomp.composition().refreshItems()
map_item = newcomp.composition()
map_item.getComposerItemById('map')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
newcomp.composition().refreshItems()
legend_item = newcomp.composition().getComposerItemById('legend')
legend_item.updateLegend()
newcomp.composition().refreshItems()
imagePath ='C:/Users/craj/Downloads/'+layer.name()+'.png'
image = newcomp.composition().printPageAsRaster(0)
image.save(imagePath,'png')

执行Python代码时发生错误:

AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas' 
Traceback (most recent call last):
File "C:/Users/craj/.qgis2/python/plugins\JoinAttribute\Join_Attribute.py", line 436, in run
map_item.setMapCanvas(canvas)
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'

最佳答案

如果你看docs QgsComposition 上没有 setMapCanvas。这个方法在其他几个类中,比如QgsComposerMap 。因此,根据调用 getComposerItemById() 的代码,您可能需要的是:

composition = newcomp.composition()
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)

关于python - 属性错误: 'QgsComposition' object has no attribute 'setMapCanvas' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com