4

I am writing a script that automatically generates a print layout. In addition to the map, the print layout should contain a table with results of a series of calculations that I have in the form of a python dictionary. While I have gotten into the workflow of adding layout items to the print layout, QgsLayoutItemTextTable seems to work differently.

This works fine:

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

title = QgsLayoutItemLabel(layout)
title.setText('MyTitle')
title.adjustSizeToText()
layout.addLayoutItem(title)

The QgsLayoutItemTextTable class, however, is for some reason not based on the QgsLayoutItem class and therefore

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

table = QgsLayoutItemTextTable(layout)
table.addRow(['hello', 'world', '!'])
layout.addLayoutItem(table)

results in the following error:

TypeError: QgsLayout.addLayoutItem(): argument 1 has unexpected type 'QgsLayoutItemTextTable'

Can anyone explain to me why this is the case and what is the intended workflow?

1 Answer 1

9

In this case to add a table the method is not the same. You need add using this addMultiFrame() because QgsLayoutItemTextTable inherits from QgsLayoutMultiFrame:

layout.addMultiFrame(table)

Minimum sample:

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

table = QgsLayoutItemTextTable(layout)
layout.addMultiFrame(table)

# Add columns       
cols = [QgsLayoutTableColumn(),QgsLayoutTableColumn(),QgsLayoutTableColumn()]
cols[0].setHeading("heading 0")
cols[1].setHeading("heading 1")
cols[2].setHeading("heading 2")
table.setColumns(cols)

# Add only 1 row
table.setContents([['hello', 'world', '!']])

# Base class for frame items, which form a layout multiframe item.
frame = QgsLayoutFrame(layout, table)
frame.attemptResize(QgsLayoutSize(30, 30), True)
table.addFrame(frame)
4
  • Thank you so much for the quick answer! Unfortunately, just swapping this one line did not work for me. I don't get an error anymore but the table is still not added to the print layout. Could you please extent your answer to a complete minimum example workflow?
    – lueho
    Commented Jul 26, 2019 at 9:46
  • Added a minimum example
    – Fran Raga
    Commented Jul 26, 2019 at 12:01
  • 1
    Wonderful, thank you! This example should find it's way into the PyQGIS Developer Cookbook
    – lueho
    Commented Jul 26, 2019 at 12:12
  • Your welcome!I will add it these days there
    – Fran Raga
    Commented Jul 26, 2019 at 12:17

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.