我正在尝试使用QGis Map composer保存地图及其图例。我已经有模板。
这是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'
答案 0 :(得分:1)
如果您查看docs setMapCanvas
上没有QgsComposition
。此方法在其他几个类中,例如QgsComposerMap
。因此,根据调用getComposerItemById()
的代码,您可能需要的是:
composition = newcomp.composition()
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)