I noticed a strange behavior when creating a new
QgsFeature object and adding it to a layer, inside a QGIS plugin. Let me first briefly explain the structure of my plugin: I have a main function that iterates on the features of a layer and calls two subfunctions at each iteration (let call them
subfunction2). Basically, this can be seen as:
main function | for … | | subfunction1 | | subfunction2
subfunction1, I create a new
newFeature = QgsFeature() # newFeature.id() gives 0, which is normal newFeature.setGeometry( … ) newFeature.setAttributes( f1.attributes() ) … dataProvider.addFeatures( [newFeature] )
Now, here's the issue: after adding
newFeature to the dataProvider,
newFeature.id() keeps giving 0 in the rest of
subFunction1 and in
subFunction2. However, in the next iteration,
newFeature.id() gives a correct, incremented id in all subfunctions.
Note that if I choose a specific id for
newFeature (e.g. if I write
newFeature = QgsFeature( 99 ) instead of
newFeature = QgsFeature()), the problem remains the same. The specified id is overwritten by an automatic id, in the next iteration only. Everything else (geometry, attributes) is fine.
So my question is: when is
newFeature's id supposed to be set by the
QgsFeature class (or anything else)? Clearly, it is not immediate but has to wait some trigger. I googled the issue and tried to browse the C++ source, but it didn't help me much.