I would like to repeat this script on hundreds of layers using PyQGIS 3.16.
I wanted to import it in the Modeler from the QGIS toolbox and then run the script in a batch process to select my hundreds of layers. The problem is that I can't switch from the Python console to the QGIS toolbox, I systematically get errors ("iface is not defined", "SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x8e....") and I can't solve them... I also tried to make the script in the same table according to the attributes of a field "name" to repeat it when the name of the object changes but nothing happens using the function: "getFeature()" but the loop does not happen.
Would you have a solution?
from qgis.utils import iface
from PyQt5.QtCore import QVariant
layer = iface.activeLayer() #Click layer in layer tree
idfield = 'num_page_1' #Change to match the name of your field
coords = [[round(f.geometry().centroid().asPoint().x(),0),round(f.geometry().centroid().asPoint().y(),0),f.id()] for f in layer.getFeatures()]
coords.sort(key=lambda k: (k[1],-k[0]), reverse=True)
order = [i[2] for i in coords]
i = layer.fields().indexFromName(idfield)
attrMap = {id: {i:e} for e,id in enumerate(order,1)}
layer.dataProvider().changeAttributeValues(attrMap)