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 小时前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试
bobz9653 小时前
tcp/ip 中的多路复用
后端
bobz9653 小时前
tls ingress 简单记录
后端
你的人类朋友4 小时前
什么是OpenSSL
后端·安全·程序员
bobz9654 小时前
mcp 直接操作浏览器
后端
前端小张同学7 小时前
服务器部署 gitlab 占用空间太大怎么办,优化思路。
后端
databook7 小时前
Manim实现闪光轨迹特效
后端·python·动效
武子康8 小时前
大数据-98 Spark 从 DStream 到 Structured Streaming:Spark 实时计算的演进
大数据·后端·spark
该用户已不存在8 小时前
6个值得收藏的.NET ORM 框架
前端·后端·.net
文心快码BaiduComate8 小时前
文心快码入选2025服贸会“数智影响力”先锋案例
前端·后端·程序员