Sunday, 13 September 2015

How to get a composer label by ID with Python in QGIS?


I have a script that was working, where I was able to grab a composer label by its ID and then update its text by doing the following:


labelTitle = myComposition.getComposerItemById('pageTitle')
labelTitle.setText('New Title')


But after updating to the latest version of QGIS, it looks like labelTitle is coming back as a QgsComposerItem type instead of QgsComposerLabel, so it is throwing the error 'QgsComposerItem' object has no attribute 'setText'


Is there a way to cast it as a label, or am I missing something? Or is there an entirely better way to accomplish this?



Answer



Another workaround suggested by Nyall Dawson (cast) :


from qgis.core import QgsProject, QgsLayoutItemPicture
import sip
myLayout = QgsProject.instance().layoutManager().layoutByName('test')
myLayoutPicture = sip.cast(myLayout.itemById("picture"), QgsLayoutItemPicture)
myLayoutPicture.setPicturePath("path to an image")

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...