Skip to main content
1 of 2
Bera
  • 77.8k
  • 14
  • 78
  • 188

This will automatically refactor fields accouring to the current order of the attribute table:

layer = QgsProject.instance().mapLayersByName("points")[0] #Change points to the name of your layer

#Create a dictionary of current field order and the field properties:
default_fields = {f.name():{'expression':f.name(),'length':f.length(),'name':f.name(),'precision':f.precision(),'sub_type':f.subType(),'type':f.type(),'type_name':f.typeName()} for f in layer.fields()}

#For example to get the properties of the KKOD field:
#default_fields['KKOD']
#{'expression': 'KKOD', 'length': 5, 'name': 'KKOD', 'precision': 0, 'sub_type': 0, 'type': 2, 'type_name': 'Integer'}

#Find the current field order accourding to the attribute table configuration:
tableconfig  = layer.attributeTableConfig()
new_field_order = [c.name for c in tableconfig.columns()] #The current order in the attribute table

#Remap the fields 
newfieldmap = [default_fields[newfield] for newfield in new_field_order if newfield in default_fields]

processing.runAndLoadResults("native:refactorfields", {'INPUT':layer,
    'FIELDS_MAPPING':newfieldmap,'OUTPUT':'TEMPORARY_OUTPUT'})

enter image description here

Bera
  • 77.8k
  • 14
  • 78
  • 188