6

I'm trying to develop a plugin in QGIS 2.6, which opens a composer, add a map and a legend, and (among other things) adjusts the legend.

Is there a way to go through items in a composer legend with PyQgis? What I'd want in the end is to change the item name, depending on the type of item (group, raster ...).

Here is my code:

for legend in self.composition.items():
    if isinstance(i,QgsComposerLegend):
        legend.setAutoUpdateModel(True)
        legend.setLegendFilterByMapEnabled(True)            
        for item in legend.items():
            if item.itemtype() == QgsComposerLegendItem.GroupItem:
                groupItem.setUserText() = 'another text'

Qgis answers that QgsComposerLegend has not attribute called "items" (which I expected). I looked for a property to iterate on legend items, and I have not found it in the API documentation nor in web searches.

1 Answer 1

6

Finally I found the answer : using the QgsLegendModelV2()class, and its functions inherited from QgsLayerTreeModel : "index(i,j)" to select each legend item and "rowcount" to obtain the rows number. All in a "for x in xrange" loop.

That gives:

for i in self.composition.items():
    if isinstance(i,QgsComposerLegend):
        legend = i
        for i in xrange(legend.modelV2().rowCount()):
            posteleg=legend.modelV2().index(i, 0)
            print posteleg.data()

Best regards

1
  • 2
    This way you get the item name. But how do you change it?
    – DMS02
    Commented Dec 20, 2016 at 11:05

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.