Skip to content

Instantly share code, notes, and snippets.

@olivierdalang
Last active December 10, 2015 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save olivierdalang/4437246 to your computer and use it in GitHub Desktop.
Save olivierdalang/4437246 to your computer and use it in GitHub Desktop.
computeFieldIndex = layer.fieldNameIndex( 'population' )
allFieldsMap = layer.pendingFields()
expression = QgsExpression('"affected" = 1')
expression.prepare(allFieldsMap)
if expression.hasParserError():
raise Exception('Parser error !!')
if self.selectedOnly: #if we want to loop through selection only
features = layer.selectedFeatures()
for feature in features:
result = expression.evaluate(feature)
if expression.hasEvalError():
raise Exception('Eval error !!')
if result.toBool():
total += feature.attributeMap()[ computeFieldIndex ].toDouble()[ 0 ]
else: #if we want to loop through the whole layer
layer.select( range(0,len(allFieldsMap)), QgsRectangle(), True )
feature = QgsFeature()
while layer.nextFeature( feature ):
result = expression.evaluate(feature)
if expression.hasEvalError():
raise Exception('Eval error !!')
if result.toBool():
total += feature.attributeMap()[ computeFieldIndex ].toDouble()[ 0 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment