2

Part of my QGIS plugin is responsible for appending a new column to a vector layer and fill this column with values calculated earlier.

I'm able to append the column using

layerPoly = QgsMapLayerRegistry.instance().mapLayersByName(PolyName)[0]
layerPoly.dataProvider().addAttributes([QgsField(newName, QVariant.Double, "double", 10, 2)])
layerPoly.updateFields()

So far it works, creating a new field of a double type, length 10 and precision 2.

Now starts the part of updating attributes of each feature:

columnid = layerPoly.fieldNameIndex(PolyName)

layerPoly.startEditing()

for feature in range(len(self.polygons)):
    # self.polygons is a list of features from layerPoly

    feat = self.polygons[feature]
    fid = feat.id()

    # self.y is a list of values that has length same as self.polygons
    item = round(self.y[feature],2)

    layerPoly.changeAttributeValue(fid, columnid, item)

layerPoly.commitChanges()
  • print type(fid) returns type: long instead of QgsFeatureId as I think it should?
  • print type(columnid) returns type: int
  • print type(item) returns type: float

What causes the changeAttributeValue to be False? I thought it's fid's type not QgsFeatureID but int, but compared to other codes I have seen on the Internet, this fid, feat.id() part is quite the same, so it shouldn't be an issue.

I'm using QGIS 2.8 and PyQt4==4.11.4.

  • hi, it's self.polygons = [feature for feature in layerList_Poly[0].getFeatures()]. self.polygons are a correct list, because I use this list to fill a qTableWidget somewhere else in the code. – adamczi Sep 14 '16 at 13:33
  • Yes, way before, I also read the types just before this changeAttributeValue, I can also print contents of this list just a line above it – adamczi Sep 14 '16 at 17:12
  • Have you checked the datatype of the variable item? The code all looks fine, I can only assume it's a datatype issue? – Liam G Sep 14 '16 at 23:35
  • I'm sure I wrote it up here, but somehow it disappeared... The type is float (data are xxx.xx values). I edited the question. – adamczi Sep 15 '16 at 6:52
  • I tried looping over features and so calling 'fresh' feature.id(), with same result. I couldn't make setFields work, documentation says it was introduced in Q 2.9, I'm using 2.8 and can't really have the newest version. – adamczi Sep 15 '16 at 7:45
2

The problem was in columnid variable. Although it was of type int, the columnid = layerPoly.fieldNameIndex(PolyName) somehow was returning -1 what was not a valid column id. The rest of code is fine.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.