Monday, 15 October 2018

pyqgis - Id allocation of QgsFeature objects


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.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...