1

This scripts works fine for me, but every time its called, a new composer-template is created (Composer 1, Composer2 etc). If the user saves the project, also the composers are saved and the list grows up...

So I want to remove the new item OR name it, so only one of them is in the list:

from qgis.PyQt.QtXml import QDomDocument
from qgis import gui

scale = 10000
templateFile='c:/1temp/mylayout.qpt'
activetool = 15# 'MoveItemContent'

composerview = iface.createNewComposer()
#load template
f= file(templateFile, 'r')
templateContent = f.read()
f.close()
doc=QDomDocument()
doc.setContent(templateContent)
composerview.composition().loadFromTemplate(doc)
#show composer
composerview.show()
#setup map
map = composerview.composition().getComposerMapById(0)#QgsComposerMap
#extent
map.zoomToExtent(iface.mapCanvas().extent())
#scale
if scale >0:
    map.setNewScale(int(scale))
#set activetool
if activetool is not None and activetool<>'':
    composerview.setCurrentTool(gui.QgsComposerView.Tool(activetool))
#finally
composerview.composition().refreshItems()

2 Answers 2

2

It basically breaks down to setting windowTitle of the element, what is a property inherited from QWidget. Methods are setWindowTitle and windowTitle as described in the docs. More complete example below:

# Get composer file contents
path = '' # path to .qpt file
with open(path, 'rt') as f:
    content = f.read()

# Load the content into new Composer element
myDocument = QDomDocument()
myDocument.setContent(content)
newComposition = self.iface.createNewComposer()
newComposition.composerWindow().setWindowTitle('My composition') # <-- set the name here
newComposition.composition().loadFromTemplate(myDocument)

# Access available compositions
composers = self.iface.activeComposers()
for item in composers:
    if item.composerWindow().windowTitle() == 'My composition':
        doSomething(item)
1
  • Thank you, but I tried something similar before. The window title has nothing to do with the name of the composer template, so it changes nothing: every time you run it, a new item in the composer manger is created with its default name.
    – The Rabbit
    Commented Mar 5, 2018 at 13:01
0

I solved this problem for myself like this: def getComposerByName(self, composerName): composers = self.iface.activeComposers() for composer in composers: if composer.composerWindow().windowTitle() == composerName: return composer

... composer = getComposerByName(self, 'myComposer') if composer is None: composer = self.iface.createNewComposer('myComposer') composer.composerWindow().show() ...

1
  • Thx a lot :) I had something similar, but your post pushed me to the right direction!
    – The Rabbit
    Commented Apr 18, 2018 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.