QGIS – Automatically Sorting Table Data by Specified Column When Opening Attribute Table

attribute-tabledefaultfields-attributesqgissorting

I want the attribute table in QGIS to be automatically sorted by the column I want, so that I don't have to click on the right column every time.

At the moment, when I open the attribute table, the sorting is done on the "ID" column, and the numbers are in random order, not in descending or ascending order.

Is this currently possible?

enter image description here

Best Answer

Let's assume there is a point layer called 'points_test' with its attribute table, see image below.

input

As you can see there are two fields in it:

Name:id   | TypeName:Integer | Type:2  | Length:1
Name:TEST | TypeName:String  | Type:10 | Length:10

By default my values in the attribute table are sorted by "id" fields. How one can know that?

Open Attribute Table (F6) and proceed with Right Mouse Click on the column header > Sort...

attribute_table

Now, I will configure attribute table sort order and switch to another field. In the pop-up window insert the desired field, in my case it is "TEST", instead of "id".

sort

And now as you can see that my attribute table was visually changed into different sorting order evoked from the "TEST" field.

result


The same action can be performed with PyQGIS.

Proceed with Plugins > Python Console > Show Editor and paste the script below

layer = iface.activeLayer()

config = layer.attributeTableConfig()

config.setSortExpression("TEST") # name of the field
config.setSortOrder(0) # 0:ascending 1:descending

layer.setAttributeTableConfig(config)

iface.showAttributeTable(layer)

Press Run script run script and get the output the same as was achieved above.


References:

Related Question