[GIS] Getting Id of selected feature in QcomboBox of PyQGIS

pyqgis

I have a QcomboBox that shows attributes from a field, each attribute occurs only one time. I am trying to get the id of the selected attribute\feature so I can then use setSelectedFeatures(), and then zoomToSelected().
I though there are similar examples, I can’t figure out how to get only the id of the selected feature.

Does anybody have a suggestion?

here is my code:

def run(self):
    """Run method that performs all the real work"""
    layer = iface.addVectorLayer("C:\Users\carmel.han\Documents\QGIS\qgis_sample_data\shapefiles/regions.shp",
                                 "regions", "ogr")
    if not layer:
        print "Layer failed to load!"

    Feature_list = []

    self.dlg.comboBox.clear()
    for feature in layer.getFeatures():
        name =feature ["name_2"]
        Feature_list.append(name)
    self.dlg.comboBox.addItems(Feature_list)


    id=
    layer.setSelectedFeatures(id)

    iface.mapCanvas().zoomToSelected()

Best Answer

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())