3

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

1 Answer 1

5

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:

4
  • 1
    Thanks, but why are integers sorted as strings? Seems only strings are sorted correctly. Jan 27, 2022 at 9:25
  • 1
    @Taras It get saves, but does not work correctly for integer values. Jan 27, 2022 at 9:27
  • 1
    @Taras Yes, it is int4 type (the ID field). Also a field of type date is sorted incorrectly (like string values). The table is in the PostgreSQL database with PostGIS extension. Jan 27, 2022 at 9:37
  • 2
    @Taras Yes, it is a bug: github.com/qgis/QGIS/issues/34935 Jan 27, 2022 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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