如何在 QTreeWidget 中获取选中和取消选中的项目?

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

我有一个要添加项目的树形小部件。现在我需要在选择项目或取消选择先前选择的项目时调用自定义过程(注意:我正在学习 Python 和 Qt - 后者对我来说似乎有点太多了)。

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)

尝试树部件选择模型的 selectionChanged 信号:

        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)))