Monday 26 June 2017

pyqgis - Selecting and updating attribute values using Python console in QGIS?


I am working with Landusefc and Class columns (ref table).


What I want is: Selecting all water from "Class" and giving a value say '8' in the "Landusefc" column for these selected features.


Table looks like


Test table I have tried the following code, it works till the selection part but doesn't seem to change the attribute value using the ChangeAttributeValue.


from qgis.core import *
import processing

layer=processing.getObject('test1')
query= ' "class" = \'Water\' '
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.setSelectedFeatures([k.id() for k in selection])

#using change Attribute to change the value of the selected feature

layer.startEditing()
for feat in selection:
layer.changeAttributeValue(feat.id(), 5, 8)


layer.commitChanges()

Answer



SOLUTION 1:


You have to remove layer.setSelectedFeatures([k.id() for k in selection]).


Because selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query)) line gives you a QgsFeatureIterator, that's an iterator. When you use that iterator once, you reach the end of the iterator. Then, if you use it again, you get nothing.


In your case, when you use selection variable (it's an iterator now) in [k.id() for k in selection], you reach the end. If you use selection in for loop, since you are at the end of the iterator, you don't have any feature now. If you want to be certain, you can add a print("Foo") line to for loop.


SOLUTION 2:


Change for feat in selection: into for feat in layer.selectedFeatures():. This solution works only on QGIS 2.x.


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...