qgis – Getting Field Names with QGIS Expressions in Same Order as in Attribute Table

expressionfields-attributesqgisqgsexpressionsorting

Context

I want to get a list of field names of a layer using QGIS expressions. The function attributes() returns a key:value map of the attribute names and values. By default, the result is sorted alphabetically based on the attribute name. To get an alphabetical list of attribute names alone, I can use map_akeys(attributes()). This works fine. For those interested: the question arose with this use case.

Question

How can the sort order be changed so that the order is not alphabetical, but reproduces the order in the attribute table?

Alphabetical sort order does not correspond to the order in the attribute table:

enter image description here

What I tried

A workaround for a custom order is ordering it manually with the new array_prioritize function (available since QGIS 3.20). However, the sort order has to be defined manually and thus eliminates the advantage of automatically getting a list of all attributes with map_akeys(attributes()):

array_prioritize(
    map_akeys(attributes()),
    array ('grassland','forest','steppe','other','value5','value6','value7','value8','value9','value10','value11', 'value12')
)

enter image description here

Best Answer

A simple custom function will do that :

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='GIS SE', referenced_columns=[])
def ordered_fields(feature, parent):
    return feature.fields().names()

To use : ordered_fields()