1

I am trying to go through a for loop in QGIS's Python module in reverse order for my features.

from qgis.utils import iface
from PyQt4.QtCore import *
layers = iface.legendInterface().layers()
for layer in layers:
    name = layer.name()
    myLayer = QgsMapLayerRegistry.instance().mapLayersByName( name )[0]
    if name.startswith('Test'):
        for f in layer.getFeatures():

I would like to be able to go through that second for loop in reverse order. I know python has the reversed() function but that is only for lists. I can't seem to use it for layer.getFeatures().

Is there a way to do this?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
efrank
  • 419
  • 2
  • 11
  • 2
    Perhaps you could do something like "features = sorted(layer.getFeatures(), key=get_name)" as shown over here by walkermatt: https://gis.stackexchange.com/questions/138769/is-it-possible-to-sort-the-features-by-an-attribute-programmatically – cm1 May 31 '18 at 20:43
  • This will work for what I need! Thanks for pointing this out – efrank May 31 '18 at 22:03

1 Answers1

2

getFeatures() by itself would return the features in an unpredictable order, so taking the reverse order is also unpredictable.

You can specify a QgsFeatureRequest containing an order by clause

from qgis.utils import iface
from PyQt4.QtCore import *
layers = iface.legendInterface().layers()
for layer in layers:
    name = layer.name()
    myLayer = QgsMapLayerRegistry.instance().mapLayersByName( name )[0]
    if name.startswith('Test'):
        #Specify the Order By clause. False means Descending
        for f in layer.getFeatures(QgsFeatureRequest().addOrderBy('IDfield',False)):
JGH
  • 41,794
  • 3
  • 43
  • 89