I have multiple projects with similar layers.
Here is an example, with all attributes (fields) visible in default order.
I do use this layout for certain tasks. But for other tasks, I wish to hide some columns and re-order others using the 'Organize Columns' option – right-click click top bar of the attribute table.
In the example below, apart from hiding some layers, I have moved the column (attributes or fields) called "Priority", and others too.
So the attribute table now looks like this…
I would like to switch between these attribute table layouts in the current layer and apply the same to other similar layers in another project.
Is this possible? Happy to consider PyQGIS solutions.
Best Answer
I can suggest a PyQGIS approach to (1) adjust, (2) export, (3) downgrade and (4) finally import configurations applied to the attribute table of a layer. It is mainly based on the
QgsAttributeTableConfig()
class and its methods.Let's assume there is a point layer called 'points_in_polygon' with a corresponding attribute table, see the image below:
The first thing to start is to analyze all the configurations that the attribute table of the layer possesses.
For the attribute table itself via the
QgsAttributeTableConfig
class:sortOrder()
sortOrder="0"
sortExpression()
sortExpression=""
actionWidgetStyle()
actionWidgetStyle="dropDown"
For the fields/columns by means of the
columns()
method, that launches theColumnConfig
structure:hidden()
hidden="0"
name()
name="id"
type()
type="field"
width()
width="-1"
Now, the following things will be executed:
Step 1 : Adjusting the attribute table of the layer
There are several useful threads that can reinforce this procedure:
They can be easily combined into a single PyQGIS script to perform this task.
For the initial attribute table, it is supposed to:
"temp"
,"avg"
, and"avg2"
columns"month"
field"city"
,"month"
, and"id"
Now the attribute table will look like this:
Check how the
QgsAttributeTableConfig
has changed:Step 2 : Exporting attribute table settings to the XML file
Export those styles to an XML file. Inspiration I found in this
QGIS/tests/src/python/test_qgsvectorlayer_namedstyle.py
dir.By means of the following code:
Now there is an XML file 'settings.xml':
Step 3 : Switching back to the default attribute table settings
Now let's revert back to the default (empty) config of the layer's attribute table.
With this piece of code:
it is possible to get this:
Step 4 : Importing attribute table settings from the XML file
On the final step let's import styles from the 'settings.xml' XML file.
With this script:
one can easily return to the custom config of the layer's attribute table:
References: