3

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

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.