Search code examples
pythonpyqt4selectionqtreewidget

How do I get the selected and deselected items in a QTreeWidget?


I have a tree-widget to which I am adding items. Now I need to call a custom procedure when the item is selected or the item previously selected is unselected (Note: I am learning both Python and Qt - the later seem to by a little too much for me).

for i in vector:
     parent = QtGui.QTreeWidgetItem(treeWidget)
     parent.setText(0, i[0])
     parent.setText(1, i[1])
     parent.setText(2,i[2])
     parent.setCheckState(0,QtCore.Qt.Unchecked)

Solution

  • Try the selectionChanged signal of the tree-widget's selection-model:

            selmodel = self.treeWidget.selectionModel()
            selmodel.selectionChanged.connect(self.handleSelection)
            ...
    
        def handleSelection(self, selected, deselected):
            for index in selected.indexes():
                item = self.treeWidget.itemFromIndex(index)
                print('SEL: row: %s, col: %s, text: %s' % (
                    index.row(), index.column(), item.text(0)))
            for index in deselected.indexes():
                item = self.treeWidget.itemFromIndex(index)
                print('DESEL: row: %s, col: %s, text: %s' % (
                    index.row(), index.column(), item.text(0)))