Search code examples
pythonpyqtpysidesignals-slotsqtreeview

How to react to keyboard selection on QtTreeView?


QTreeView has the clicked signal, but not itemChanged like QTreeWidget. I have to use QTreeView because it's "model based". Still, if my user select a row with the keyborad, clicked won't be sent, and my callback will never be called. What signal should I register to ?


Solution

  • The QTreeView class inherits QAbstractItemView, which provides access to the selection model.

    The selection model has several signals that register changes made to the current item and selection with both mouse and keyboard.

    EDIT:

    Just to be clear, the signals need to be connected like this:

    selmodel = self.listing.selectionModel()
    selmodel.selectionChanged.connect(self.handleSelectionChanged)
    

    and the signature of the handler should look something like this:

    def handleSelectionChanged(self, selected, deselected):
        indexes = selected.indexes()
        if indexes:
            print('row: %d' % indexes[0].row())
    

    with selected and deselected being instances of QItemSelection.