Monday 18 June 2018

pyqgis - Go through QGIS Python for loop through features in reverse order?


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?




Answer



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)):

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...