You have got two different approaches. Either you save the id in the combobox next to the text. Or you lookup the id based on the (unique) text, once you need it. For performance reasons, you probably want to do the first solution (since you don't have to do an extra request on selection change this way).
Using QGIS 3 (and therefore PyQt5)
for feature in layer.getFeatures():
name = feature['name_2']
slf.dlg.comboBox.addItem(name, feature.id())
id = self.dlg.comboBox.currentData()
Using QGIS 2
for feature in layer.getFeatures():
name = feature['name_2']
slf.dlg.comboBox.addItem(name, feature.id())
id = self.dlg.comboBox.itemData(self.dlg.comboBox.currentIndex())
In your script, you are editing the file directly by creating a new internal object QgsVectorLayer, not the layer in your legend.
query_point
is a "QgsVectorLayer", but lyr
is another "QgsVectorLayer" object.
Even if they are pointing to the same underlying datasource, it's two different objects. So then, when you are trying to force reloading the dataprovider, you are on the pyqgis object, you are not on the one loaded in your legend. It's TWO different layers for the QGIS point of view.
I suggest you to get the same QgsVectorLayer object from the legend. For instance :
lyr = p.mapLayersByName('query_point')[0]
.
At least at the end, when you want to reload the dataprovider, you should call the function using the layer loaded in the legend, not created in PyQGIS.
If you want to see it's two different layers :
layer_1 = QgsVectorLayer(r'path_to_my_gpkg\data.gpkg|layername=query_point', 'query_point_in_pyqgis')
print("layer_1")
print(layer_1.id())
print(layer_1.name())
layer_2 = p.mapLayersByName('query_point')[0]
print("layer_2")
print(layer_2.id())
print(layer_2.name())
It's two different layer ID.
Best Answer
You need to update the layer with the new feature values using:
So it should look something like:
Or shorten it slightly by editing and commiting the changes in one go using
with edit()
: