PyQGIS – How to Get the ID from a Selected Feature

pyqgisqgsvectorlayer

using self.iface.mapCanvas().selectionChanged.connect(self.getselectionid) how could I get the id of a manually selected feature on the Qgis map specifically on a vectorlayer? so it can be used to program a function.

I tried a couple of things to see if I could figure what selectionChanged is returning, these are my attempts and its results:

print("I selected {}".format(str(selection.feature.id())))
>>I selected <qgis._core.QgsVectorLayer object at 0x7f9d9f189c18>

print("I selected {}".format(str(selection[0].id())))
>>I selected <qgis._core.QgsVectorLayer object at 0x7f9d9f189c18>
>>I selected project_s_shapefile_f403eb35_14b9_4e61_b327_263dce57a8cb

print("I selected {}".format(str(selection)))
>>I selected <qgis._core.QgsVectorLayer object at 0x7f9d9f189c18>

Best Answer

You need to iterate over the vector layer after your signal.

def get_selection_id(layer):
    for feature in layer.selectedFeatures():
        print(feature.id())

iface.mapCanvas().selectionChanged.connect(get_selection_id)
Related Question