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 subfunction1 and subfunction2). Basically, this can be seen as:

main function
| for …
| | subfunction1
| | subfunction2

In subfunction1, I create a new QgsFeature:

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.

  • I don't know the answer, but I will make an educated guess. Since QGIS relies on GDAL for a lot of its data feature stuff, it might be one of the Python Gotchas, especially about Destroy() and saving / closing data sets, so the id gets written, after the dataset has been saved somewhere / somehow – Frank Feb 11 '16 at 9:26

The addFeatures() function returns a boolean (for success/failure) along with a list of features. You can capture these in variables:

(result, newFeatures) = vectorLayer.dataProvider.addFeatures([newFeature])

Then you can iterate through newFeatures and call the id() for each QgsFeature. If only one feature was added, you can use: newFeatures[0].id()

I found this solution here. I hope it helps!

  • @ArMoraer shouldn't this be an accepted answer? – Germán Carrillo Jul 20 '17 at 16:18

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.