2

Based in this answer to Getting features in order they are selected using PyQGIS?, I ran following code at Python Console of QGIS 3 for getting features id in order they were selected.

def onSelectionChanged():
    try:
        id = iface.activeLayer().selectedFeatures()[0].id()
        print (id)
    except IndexError:
        print ("no feature selected")

iface.activeLayer().selectionChanged.connect( onSelectionChanged )

I tried above code out with shapefile visualized at following image, where docked attributes table was used to corroborate that printed values at Python Console had correct order.

enter image description here

How can I modify my function for storing printed id values at Python Console of QGIS, as a list variable, without using a file written on disk drive?

  • If I understand well, you can define a variable out of the function and modify it inside, appending to it each new selected id. – Germán Carrillo Mar 4 '18 at 5:44
  • @Germán Carrillo Thanks for your comment. How can I do that? I tried it out and list was always empty. How can I pass a reference for redirecting values created into function to variable created outside function? – xunilk Mar 4 '18 at 13:20
2

This has worked for me from the QGIS Python console:

selected_ids = []
print(selected_ids) # prints []

def onSelectionChanged():
    try:
        id = iface.activeLayer().selectedFeatures()[0].id()
        selected_ids.append(id)
    except IndexError:
        print ("no feature selected")

iface.activeLayer().selectionChanged.connect( onSelectionChanged )

# Now select some features 

print(selected_ids) # prints [423, 347]
  • 1
    It was so easy. This is the answer. It was also considered by my. However, my issue was that I passed as parameter to the function, the ids list. Thanks a lot. – xunilk Mar 4 '18 at 14:24

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.