从 QTreeView 中的选择中获取完整的索引名称

Getting the full index name from selection in QTreeView

我使用 PyQt 创建了一个 QTreeView,在 TreeView 中,它填充了如下层次结构:

|- users
|--|-- John
|--|--|--- graphics
|--|-- Alice

在我的 TreeView 中,我选择了 graphics

虽然我能够按如下方式获取选择的索引/名称:

for sel in self.tree_view.selectedIndexes():
    sel_name = sel.data()

以上代码只会 return 我 graphics。我怎样才能得到 'full' 路径,这样它将 return 我 '/users/John/graphics'?

要获取完整的索引名称,您必须遍历父项,如下所示:

for sel in self.tree_view.selectedIndexes():
    val = "/"+sel.data()
    while sel.parent().isValid():
        sel = sel.parent()
        val = "/"+ sel.data()+ val
    print(val)

示例:

from PyQt5 import QtCore, QtGui, QtWidgets

tree = {
'users': {
    "John" : ["graphics"],
    "Alice": []
    }
}

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.tree_view = QtWidgets.QTreeView()
        self.setCentralWidget(self.tree_view)

        model = QtGui.QStandardItemModel()
        self.populateTree(tree, model.invisibleRootItem())
        self.tree_view.setModel(model)
        self.tree_view.expandAll()
        self.tree_view.selectionModel().selectionChanged.connect(self.onSelectionChanged)

    def populateTree(self, children, parent):
        for child in children:
            child_item = QtGui.QStandardItem(child)
            parent.appendRow(child_item)
            if isinstance(children, dict):
                self.populateTree(children[child], child_item)

    def onSelectionChanged(self, *args):
        for sel in self.tree_view.selectedIndexes():
            val = "/"+sel.data()
            while sel.parent().isValid():
                sel = sel.parent()
                val = "/"+ sel.data()+ val
            print(val)


if __name__ == '__main__':
    import sys

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