I'm scripting in QGIS 3.6 using python. Looking at the API and trying out attribution-editing functions, I found that a vector layer has a QgsVectorLayer::fields() set of fields, and the features inside have a set of QgsFeature::fields().

If I use addAttribute() on the layer (in between the startEditing and commitChanges guards), then immediately query a layer-feature's fields, I find that the fields are out of sync (new field is in the layer's fields, but not in the feature's fields) and calling feature.setAttribute() with the new string fails with a key error.

I'm wondering: 1. if there is a practical need to have these things out of sync (ie: is it ever desirable / useful) 2. what normal people do to keep layer & feature fields in sync, if it is undesirable. Is there a simple call where I can flush the layer's fields into all the features fields quickly?


Ok I see the hangup. I was following the "Adding and removing fields" section of the "using vector layers" part of the pygis cookbook. This includes a call to updatefields(). What they don't tell you is this set of operations constructs new qgisfeature objects rather than changing the existing ones, and sticks the fresh ones into the vector layer's feature list. This design caused my feature pointers to point to a feature that was no longer associated with the layer. I can "get the new feature" by getting the index number of the feature using the Id() method, then do layer.getfeature(Id)

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