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 = []

    for feature in layer.getFeatures():
        name =feature ["name_2"]



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())
  • The line : id = self.dlg.comboBox.currentData() Is causing problems: AttributeError: 'QComboBox' object has no attribute 'currentData' I tried to check the imports the spelling and finally tried a different approach, which failed also: id = self.dlg.comboBox.itemData(self.dlg.comboBox.currentIndex()) TypeError: QgsVectorLayer.setSelectedFeatures(unknown-type): argument 1 has unexpected type 'NoneType'
    – Carmel Han
    Mar 1 '18 at 8:58
  • do you have any idea why 'currentData' is not recognized?
    – Carmel Han
    Mar 1 '18 at 10:25
  • I assume you are working on QGIS 2. currentData is only available starting from QGIS 3. Maybe the second error you get is because there is no item selected? Mar 1 '18 at 12:54

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.