PyQt 高级部分实战

在这篇文章中,我们将通过一个实战项目来综合运用之前学习的 PyQt 高级部分的知识。我们将创建一个简单的文件管理器。

项目需求

  • 文件和文件夹列表展示
  • 打开文件和文件夹
  • 删除文件或文件夹
  • 数据库记录用户操作

环境准备

确保你已经安装了 PyQt5 和 PyQt5-sip。

bash 复制代码
pip install PyQt5 PyQt5-sip

代码实现

主窗口

首先,我们创建一个主窗口来展示文件和文件夹。

python 复制代码
from PyQt5.QtWidgets import QMainWindow, QTreeView, QFileSystemModel, QVBoxLayout, QWidget, QPushButton
from PyQt5.QtCore import QDir

class FileManager(QMainWindow):
    def __init__(self):
        super().__init__()

        self.fileSystemModel = QFileSystemModel()
        self.fileSystemModel.setRootPath(QDir.rootPath())

        self.tree = QTreeView()
        self.tree.setModel(self.fileSystemModel)
        self.tree.setRootIndex(self.fileSystemModel.index(QDir.rootPath()))

        self.deleteButton = QPushButton("Delete")
        self.deleteButton.clicked.connect(self.delete_item)

        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        layout.addWidget(self.deleteButton)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

删除功能

我们添加一个按钮来删除选中的文件或文件夹。

python 复制代码
from PyQt5.QtWidgets import QMessageBox

def delete_item(self):
    index = self.tree.currentIndex()
    file_path = self.fileSystemModel.filePath(index)

    msgBox = QMessageBox()
    msgBox.setText(f"Are you sure you want to delete {file_path}?")
    msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    returnValue = msgBox.exec()

    if returnValue == QMessageBox.Yes:
        self.fileSystemModel.remove(index)

数据库记录

我们使用 SQLite 数据库来记录用户的删除操作。

python 复制代码
from PyQt5.QtSql import QSqlDatabase, QSqlQuery

def init_db(self):
    self.db = QSqlDatabase.addDatabase("QSQLITE")
    self.db.setDatabaseName("file_manager.db")

    if not self.db.open():
        print("Cannot open database")
        return

    query = QSqlQuery()
    query.exec_("CREATE TABLE IF NOT EXISTS operations (id INTEGER PRIMARY KEY, action TEXT, path TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)")

delete_item 方法中,我们添加数据库记录。

python 复制代码
def delete_item(self):
    # ... (existing code)
    if returnValue == QMessageBox.Yes:
        query = QSqlQuery()
        query.prepare("INSERT INTO operations (action, path) VALUES (:action, :path)")
        query.bindValue(":action", "delete")
        query.bindValue(":path", file_path)
        query.exec_()
        self.fileSystemModel.remove(index)

完整代码

将以上代码片段整合,形成完整的文件管理器应用。

运行

运行你的代码,你将看到一个简单但功能完整的文件管理器。

这就是我们的 PyQt 高级部分实战项目。通过这个项目,你应该能更好地理解如何在实际应用中使用 PyQt 的高级功能。

相关推荐
寻月隐君2 分钟前
Solana 开发实战:Rust 客户端调用链上程序全流程
后端·rust·web3
丘山子40 分钟前
别再滥用 None 了!这才是 Python 处理缺失值的好方法
后端·python·面试
error_cn1 小时前
postgresql视图与触发器
后端
知秋丶1 小时前
Spring-rabbit重试消费源码分析
java·后端·spring
error_cn1 小时前
tekton部署与初始化步骤
后端
Victor3561 小时前
MySQL(77)如何设置自动备份任务?
后端
同志们1 小时前
一文弄懂用Go实现MCP服务:从STDIO到Streamable HTTP的完整实现
后端·llm
丘山子1 小时前
Python 字典是有序数据结构吗?是你以为的那种有序吗?
后端·python·面试
天天摸鱼的java工程师1 小时前
synchronized 与 ReentrantLock 区别?公平锁、非公平锁、可重入锁、自旋锁的原理与应用?
java·后端
程序员麻辣烫1 小时前
模型Function Call
后端·llm