Friday 20 March 2015

qgis - How to access a specific feature?


Is it possible to go to a specified row number (or perhaps the next/previous) row using PyQGIS?


This code gets the value of the first attribute in the first row of the table



features = aLayer.getFeatures()
attrs = feat.attributes()
attribute0 = attrs[0]
print attribute0

How can I get the value of the same column (0), for row 2, 22, 222...? Is there a way to do this without using a for loop?



Answer



You could access the specific feature, without a loop, using the setFilterFid() method.


In your case, if you wanted to call the feature in row 222, you would do:


aLayer = iface.activeLayer()


request = QgsFeatureRequest().setFilterFid(222)
feat = aLayer.getFeatures(request).next()
print feat.attributes()


To just get a specific attribute, you would use


feat['COLUM_NAME']

or



feat.attributes()[INDEX]

instead of feat.attributes() in the snippet above.


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