125
社区成员




实现效果:
要实现可选择路径的文件树状管理,你可以扩展前面的示例,并添加选择路径的功能。下面是一个更新的示例代码,演示了如何使用 PyQt 实现可选择路径的文件树状管理器:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QFileSystemModel, QVBoxLayout, QWidget, QPushButton, QLabel
class FileTreeWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("File Tree Example")
self.setGeometry(100, 100, 800, 600)
# 创建文件系统模型
self.model = QFileSystemModel()
self.model.setRootPath("") # 设置根路径为空,显示整个文件系统树
# 创建树视图
self.tree_view = QTreeView(self)
self.tree_view.setModel(self.model)
self.tree_view.setRootIndex(self.model.index("")) # 设置根索引为根路径的索引
# 创建选择路径按钮和标签
self.select_button = QPushButton("选择路径")
self.select_button.clicked.connect(self.select_path)
self.path_label = QLabel("当前路径:")
# 布局
layout = QVBoxLayout()
layout.addWidget(self.select_button)
layout.addWidget(self.path_label)
layout.addWidget(self.tree_view)
# 创建主窗口的中心部件
central_widget = QWidget(self)
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def select_path(self):
# 打开文件选择对话框,选择路径
path = QFileDialog.getExistingDirectory(self, "选择路径", "")
if path:
# 设置模型的根路径为选择的路径
self.model.setRootPath(path)
self.tree_view.setRootIndex(self.model.index(path))
self.path_label.setText(f"当前路径:{path}")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FileTreeWindow()
window.show()
sys.exit(app.exec_())
在这个更新的示例中,添加了一个选择路径的按钮和一个标签来显示当前选择的路径。当点击选择路径按钮时,会弹出一个文件选择对话框,可以选择文件系统中的路径。选择路径后,我们将该路径设置为模型的根路径,并更新树视图的根索引和路径标签的显示。
为了使用 QFileDialog
类打开文件选择对话框,我们需要在代码开头添加以下 import 语句:
from PyQt5.QtWidgets import QFileDialog
请确保安装了 PyQt5 库,并运行示例代码。你可以选择路径,并在窗口中浏览和管理该路径下的文件和文件夹。选定的路径将在标签中显示。
c++实现亦是类似如此!