如何在 QTreeWidget 中获取点击的项目?

How do I get a clicked item in a QTreeWidget?

我有一个二维的QTreeWidget,如何通过点击得到一个Item?我使用 PyQt5。我有这部分代码,但它只获取所选行的第一项(或通过更改 baseNode.text(#))

获取任何其他项
...
self.treeWidget.itemSelectionChanged.connect(lambda: loadAllMessages())
def loadAllMessages():
    getSelected = self.treeWidget.selectedItems()
    if getSelected:
        baseNode = getSelected[0]
        getChildNode = baseNode.text(0)
        print(getChildNode) 
...

您只需使用 QTreeWidgetItem 发送的 itemClicked 信号和点击的列:

示例:

from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        tree = QtWidgets.QTreeWidget()
        tree.setColumnCount(2)
        lay.addWidget(tree)

        for i in range(4):
            parent_it = QtWidgets.QTreeWidgetItem(["{}-{}".format(i, l) for l in range(2)])
            tree.addTopLevelItem(parent_it)
            for j in range(5):
                it = QtWidgets.QTreeWidgetItem(["{}-{}-{}".format(i, j, l) for l in range(2)])
                parent_it.addChild(it)
        tree.expandAll()

        tree.itemClicked.connect(self.onItemClicked)

    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
    def onItemClicked(self, it, col):
        print(it, col, it.text(col))


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())