我已经使用PyQt创建了一个QTreeView
,其中在TreeView中,其填充的层次结构如下:
|- users
|--|-- John
|--|--|--- graphics
|--|-- Alice
在TreeView中,我选择了graphics
。
虽然我可以按如下方式获得所选内容的索引/名称:
for sel in self.tree_view.selectedIndexes():
sel_name = sel.data()
上面的代码只会返回我graphics
。我如何获得“完整”路径,这样它将返回“ / users / John / graphics”?
答案 0 :(得分:2)
要获取完整索引名,您必须遍历父母,如下所示:
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_())