I am writing a plugin for QGIS (v2.12).
There have been quite a few similar questions on this forum, but they don't seem to work for me. My plugin does the following:
- get the vector layer
- check that it is a line shapefile.
- get the raster layer
- look at the vector layer, if there isn't a attribute named 'slope' add it.
- step through each line in the shape layer and compute the slope.
- change the attribute value for that line to the computed slope.
My problem is the last step, I can compute the slope, set the attribute value for that field, but it never appears in the attribute table after the plugin completes.
Here is the relevant code, the logMessages are all valid, the # comments are things I have tried. I like setAttribute the best.
selectedVectorLayer.startEditing()
for line in selectedVectorLayer.getFeatures():
slope = self.getLineSlope(line, rasterData)
columnid = selectedVectorLayer.fieldNameIndex('slope')
QgsMessageLog.logMessage("id: {} segment: {} Slope: {}".format(line.attribute('id'), line.attribute('segment'), slope) , 'LineSlopes', QgsMessageLog.INFO)
#line.changeAttributeValues(line.id(), columnid, slope)
#attrib = {0: line.id(), 1: line.attribute('segment'), 2: slope }
#selectedVectorLayer.dataProvider().changeAttributeValues({line.id(): attrib})
line.setAttribute('slope', slope)
QgsMessageLog.logMessage("id: {} segment: {} Slope: {}".format(line.attribute('id'), line.attribute('segment'), line.attribute('slope')) , 'LineSlopes', QgsMessageLog.INFO)
selectedVectorLayer.commitChanges()
I'm thinking that there has to be something simple that I have overlooked.
Returns false if attribute name could not be converted to index. Field map must be associated using setFields before this method can be used.
... did you callsetFields()
to create the field map?