5

I have an attribute table in my layout, defined as follow :

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

pdf = QgsProject.instance().mapLayersByName('plan_de_ferme')[0]
pdf_table = QgsLayoutItemAttributeTable.create(layout)
pdf_table.setVectorLayer(pdf)
pdf_fields = ['champ','sup','supepnd']
pdf_table.setDisplayedFields(pdf_fields, True)

I would like to rename the fields name displayed in the layout without changing the fields name in the layer.

I tried :

pdf_headers = ['Champ','Superficie (ha)','Superficie épandable (ha)']
pdf_table.setHeading(pdf_headers)

Like it's the way to do with a QgsLayoutItemTextTable, but it's not working because "AttributeError: 'QgsLayoutItemAttributeTable' object has no attribute 'setHeading'".

2 Answers 2

7

You can use the code snippet below:

pdf_headers = ['Champ','Superficie (ha)','Superficie épandable (ha)']

#retrieve layout table columns
cols = pdf_table.columns()

#construct a new list containing cloned QgsLayoutTableColumn objects
new_cols = [col.clone() for col in cols]

#iterate the cloned columns and use setHeading() method to set each
#column's header cell contents to the corresponding item from pdf_headers
for i, cloned_col in enumerate(new_cols):
    cloned_col.setHeading(pdf_headers[i])
    
#set pdf_table columns from the list of cloned and modified
#column objects with new heading contents
pdf_table.setColumns(new_cols)

#refresh layout
layout.refresh()

I tested this code and obtained the following results.

Layout table before:

enter image description here

Layout table after:

enter image description here

While column names in layer remain unchanged:

enter image description here

1
  • That works great, thank you !! Commented Jan 21, 2021 at 17:18
3
  • Assign pdf_table.columns() to a variable

    columns = pdf_table.columns()
    
  • Make changes

    for column, header in zip(columns, pdf_headers):
        column.setHeading(header)
    
  • Use setColumns

    pdf_table.setColumns(columns)
    layout.refresh()
    

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.