Home > qgis > Get features in order they are selected using QGIS

Get features in order they are selected using QGIS

August 30Hits:1

Is there a way of establishing the order that a user selected features using QGIS and Python?

By example: we have a network of line features representing a road network, and the user defines a route from point A to point B. Currently, using layer.selectedFeatures() returns the correct features, but in the order they were drawn rather than the order they were selected.

I've tried a few things to do this manually:

  • QgsMapToolEmitPoint(canvas) obviously doesn't work - I want the feature not the point clicked. But I guess in worst case I could hack a spatial query to do a look up of the closest feature. Not ideal.
  • QgsMapToolSelect(canvas) doesn't seem to be available as part of the Python accessible GUI or CORE, although I can find mention of it existing elsewhere.

Can anyone suggest a best case solution for this? All suggestions/tutorials/related questions appreciated.

Thanks in advance for your time, Dan


I see two possibilities:

  • Have a look at QgsSnapper (This is what you called the worst-case solution, although I don't think its bad at all. The internals would do the same)
  • Connect to the QgsVectorLayer.selectionChanged signal. In 1.9 you even get the delta of the selection.

from PyQt4.QtCore import pyqtSlot
@pyqtSlot( 'QgsFeatureIds', 'QgsFeatureIds', bool )
def onSelectionChanged( added, removed, cleared ):
    print( added )
iface.activeLayer().selectionChanged.connect( onSelectionChanged )

The @pyqtSlot line is optional. (See here for an explanation why it's good practice.)

Related Articles

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.735 s.