[英]PyQT5 QTreeWidget get full path of clicked element
I hope you all safe and healthy.我希望你们都平安健康。 My problem is simply I am trying to make a video player and I have QTreeWidget with elements (folders & files) from given path on it.我的问题只是我正在尝试制作一个视频播放器,并且我有 QTreeWidget,其中包含来自给定路径的元素(文件夹和文件)。 I want to make play video when double clicked on element in QTreeWidget.我想在 QTreeWidget 中双击元素时播放视频。
# How I create tree, fill and detect double click.
self.tree = QTreeWidget()
self.load_project_structure("resources/videos", self.tree)
self.tree.itemDoubleClicked.connect(self.handler)
def load_project_structure(self, startpath, tree):
for element in os.listdir(startpath):
path_info = startpath + "/" + element
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
if os.path.isdir(path_info):
self.load_project_structure(path_info, parent_itm)
parent_itm.setIcon(0, QIcon('img/folder.png'))
else:
parent_itm.setIcon(0, QIcon('img/file.png'))
def handler(item, column_no):
print(item, column_no)
My Tree is simply like that:我的树就是这样:
When I double click to File_1.1.2 I want to get something like that (and thats how I can play video):当我双击 File_1.1.2 时,我想得到类似的东西(这就是我播放视频的方式):
Folder_1/Folder_1.1/File_1.1.2.mp4文件夹_1/文件夹_1.1/文件_1.1.2.mp4
but I got this:但我得到了这个:
< main .Window object at 0x00000275AC0FD558> PyQt5.QtWidgets.QTreeWidgetItem object at 0x00000275AC0FD828> < main .Window object at 0x00000275AC0FD558> PyQt5.QtWidgets.QTreeWidgetItem object at 0x00000275AC0FD828>
Any help is welcome.欢迎任何帮助。 Thank you in advance先感谢您
What you have to do is iterate over the parents of the items and concatenate them:您需要做的是遍历项目的父项并将它们连接起来:
def handler(self, item, column_no):
texts = []
while item is not None:
texts.append(item.text(0))
item = item.parent()
path = "/".join(texts)
print(path)
Another simpler method is to use a role to store the full path另一种更简单的方法是使用角色来存储完整路径
def load_project_structure(self, startpath, tree):
for element in os.listdir(startpath):
path_info = os.path.join(startpath, element)
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
parent_itm.setData(0, Qt.UserRole, path_info)
if os.path.isdir(path_info):
self.load_project_structure(path_info, parent_itm)
parent_itm.setIcon(0, QIcon('img/folder.png'))
else:
parent_itm.setIcon(0, QIcon('img/file.png'))
def handler(self, item, column_no):
print(item.data(0, Qt.UserRole))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.