5

I am trying to insert a qgis attribute table to a layout using Visual Studio Code, how would I do it?

layout = project.layoutManager().layoutByName('nombre_layout')

table = QgsLayoutItemAttributeTable(layout)

layer = QgsProject.instance().mapLayersByName('nombre_capa')[0]
table.setVectorLayer(layer)
table.setDisplayOnlyVisibleFeatures(True)
table.setDisplayHeader(True) #This line doesn't work

layout.addLayoutItem(table)

table.attemptResize(QgsLayoutSize(150, 150, QgsUnitTypes.LayoutMillimeters))
table.attemptMove(QgsLayoutPoint(10, 10, QgsUnitTypes.LayoutMillimeters))

I get the error:

File "c:\Users\Desktop\Proyectos\PyQgis\script.py", line 174, in table.setDisplayHeader(True) #This line doesn't work AttributeError: 'QgsLayoutItemAttributeTable' object has no attribute 'setDisplayHeader'

1
  • What do you expect setDisplayHeader to do? Mar 17, 2023 at 12:31

1 Answer 1

8
table.setDisplayHeader(True) #This line doesn't work

Because there is no method named setDisplayHeader of table(QgsLayoutItemAttributeTable instance). Therefore, you don't need to use it.

You probably try to display header. Use

table.setHeaderMode(QgsLayoutTable.FirstFrame)

or

table.setHeaderMode(0)

It is set to QgsLayoutTable.FirstFrame by default. All options are: (Reference)

  • QgsLayoutTable.FirstFrame: 0
  • QgsLayoutTable.AllFrames: 1
  • QgsLayoutTable.NoHeaders: 2

Edit: Use layout.addMultiFrame(table) instead of layout.addLayoutItem(table).

2
  • Ahh ok, but now have a new problem. The final line(layout.addLayoutItem(table)) show error. 'File "c:\Users\Desktop\Proyectos\PyQgis\script.py", line 185, in <module> layout.addLayoutItem(table) TypeError: QgsLayout.addLayoutItem(): argument 1 has unexpected type 'QgsLayoutItemAttributeTable' Mar 30, 2023 at 10:04
  • Use layout.addMultiFrame(table) instead of layout.addLayoutItem(table). Mar 30, 2023 at 12:42

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.