使用python +pyqt5 实现类似回收站功能的实例
时间: 2024-03-30 19:36:58 浏览: 128
可以使用Python和PyQt5来实现类似回收站的功能,以下是一个简单的示例代码:
```python
import os
from PyQt5.QtCore import QFileInfo, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QMainWindow, QTreeView, QAction, QMessageBox
class RecycleBin(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Recycle Bin")
# 创建文件系统模型
self.model = QFileSystemModel()
self.model.setRootPath(os.path.expanduser('~/.local/share/Trash/files'))
# 创建树形视图
self.tree = QTreeView()
self.tree.setModel(self.model)
self.tree.setRootIndex(self.model.index(os.path.expanduser('~/.local/share/Trash/files')))
self.tree.setSortingEnabled(True)
# 创建菜单栏
self.menu = self.menuBar().addMenu("操作")
# 创建菜单项
self.restore_action = QAction("还原", self)
self.restore_action.setShortcut("Ctrl+R")
self.restore_action.triggered.connect(self.restore_selected)
self.delete_action = QAction("删除", self)
self.delete_action.setShortcut(Qt.Key_Delete)
self.delete_action.triggered.connect(self.delete_selected)
# 将菜单项添加到菜单栏
self.menu.addAction(self.restore_action)
self.menu.addAction(self.delete_action)
# 将树形视图添加到主窗口
self.setCentralWidget(self.tree)
def restore_selected(self):
# 获取当前选中的文件/文件夹
selected = self.tree.selectedIndexes()
if selected:
path = self.model.filePath(selected[0])
# 还原文件/文件夹
if os.path.isfile(path):
os.system("gvfs-trash --restore {}".format(path))
elif os.path.isdir(path):
os.system("gvfs-trash --restore {}".format(path + "/"))
self.model.refresh()
def delete_selected(self):
# 获取当前选中的文件/文件夹
selected = self.tree.selectedIndexes()
if selected:
path = self.model.filePath(selected[0])
# 显示确认删除对话框
choice = QMessageBox.question(self, "确认删除", "你确定要删除吗?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
# 删除文件/文件夹
if os.path.isfile(path):
os.system("gvfs-trash {}".format(path))
elif os.path.isdir(path):
os.system("gvfs-trash {}".format(path + "/"))
self.model.refresh()
if __name__ == "__main__":
app = QApplication([])
window = RecycleBin()
window.show()
app.exec_()
```
在上面的代码中,我们使用了`QTreeView`和`QFileSystemModel`来显示和管理回收站中的文件。我们还创建了两个菜单项来还原和删除选中的文件/文件夹。当用户选择还原菜单项时,我们使用`os.system`函数和`gvfs-trash`命令来还原文件/文件夹。当用户选择删除菜单项时,我们使用`os.system`函数和`gvfs-trash`命令来删除文件/文件夹,并使用`QMessageBox`来显示确认删除对话框,以确保用户不会意外删除文件/文件夹。
阅读全文