I'm trying to migrate a python plugin I wrote from QGIS 2.18 to QGIS 3.4. In the plugin, I'm creating new vector features and eventually adding them to an existing vector layer. I'm trying to have the added features selected automatically in QGIS after running the code described below.
For QGIS 2.18, the QgsVectorLayer
class had an addFeatures
method that contained a very convenient makeSelected
flag. When the flag was set to true, the added features were selected.
In QGIS 3.4 the addFeatures
method still exists, but the flag is gone.
I also tried to select the features using some of the class's selection methods but with no success. It seems that after adding the features to the layer, their id's change and I don't have access to these specific features and can not select them using their old ids. The only way that somehow works is assigning some sentinel value to one of the fields in all the new features and then selecting them using a query. I'd like to avoid this way because I'm afraid that at some point it can mess up a user's data.
here's an example of how I created features and added them to the current selected layer in Qgis. it can be run in the Qgis Python terminal:
layer = iface.activeLayer()
layer.startEditing()
feat = QgsFeature(layer.fields())
point_list = [QgsPointXY(0, 0), QgsPointXY(0,1), QgsPointXY(1,1), QgsPointXY(1,0), QgsPointXY(0,0)]
feat.setGeometry(QgsGeometry.fromPolygonXY(point_list))
layer.addFeature(feat)
# I'd like to add feat to the layers selection at this point
self.layer.endEditCommand()
I'm using QGIS 3.4.1 (migrating from QGIS 2.18.26), and the pyqgis API of the above versions.
I'm aware that Qgis3 uses python 3 instead of python 2.