使用PySide6开发系统界面并打包部署的完整教程
环境准备与PySide6安装
确保系统已安装Python 3.7+版本
通过pip安装PySide6:
pip install pyside6
验证安装是否成功:
import PySide6.QtWidgets
print(PySide6.__version__)
基础窗口创建
创建一个简单的空白窗口:
from PySide6.QtWidgets import QApplication, QMainWindowclass MainWindow(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("PySide6示例")self.resize(800, 600)if __name__ == "__main__":app = QApplication([])window = MainWindow()window.show()app.exec()
界面布局与控件添加
使用QVBoxLayout和QHBoxLayout进行基础布局:
from PySide6.QtWidgets import QPushButton, QVBoxLayout, QWidgetclass MyWindow(QMainWindow):def __init__(self):super().__init__()central_widget = QWidget()layout = QVBoxLayout()self.button = QPushButton("点击我")self.button.clicked.connect(self.on_click)layout.addWidget(self.button)central_widget.setLayout(layout)self.setCentralWidget(central_widget)def on_click(self):print("按钮被点击")
信号与槽机制
实现控件交互功能:
from PySide6.QtWidgets import QLineEdit, QLabelclass InteractiveWindow(QMainWindow):def __init__(self):super().__init__()self.input = QLineEdit()self.label = QLabel("输入内容将显示在这里")self.input.textChanged.connect(self.update_label)layout = QVBoxLayout()layout.addWidget(self.input)layout.addWidget(self.label)container = QWidget()container.setLayout(layout)self.setCentralWidget(container)def update_label(self, text):self.label.setText(f"当前输入: {text}")
样式表定制
使用QSS美化界面:
self.setStyleSheet("""QMainWindow {background-color: #f0f0f0;}QPushButton {background-color: #4CAF50;color: white;padding: 8px;border-radius: 4px;}QLineEdit {padding: 6px;border: 1px solid #ccc;border-radius: 4px;}
""")
打包准备
安装PyInstaller:
pip install pyinstaller
单文件打包
生成独立可执行文件:
pyinstaller --onefile --windowed --name MyApp main.py
main.spec文件的修改
# -*- mode: python ; coding: utf-8 -*-block_cipher = None# 1. 包含项目所有依赖的资源文件
a = Analysis(['main.py'], # 入口脚本pathex=['E:\\Data\\yolov5-master-int8'], # 项目根路径binaries=[],datas=[# 打包 UI 资源(图标、图片)('UI/*.jpg', 'UI'), ('UI/*.png', 'UI'), # 打包模型文件(如 best.pt)('yolov5n.pt', '.'), # 打包数据集配置(如 data.yaml)('data/coco128.yaml', '.'), # 添加 YOLOv5 核心文件(关键!)('train.py', '.'), # 训练入口脚本('detect.py', '.'), # 检测脚本(如果用到)('models/*', 'models'), # 模型配置文件('utils/*', 'utils'), # 工具类('data/*', 'data'), ],
hiddenimports=['PySide6', 'PySide6.QtCore', 'PySide6.QtGui', 'PySide6.QtWidgets','torch', 'torchvision', 'cv2', 'labelImg', 'yaml', 'PIL', 'matplotlib','utils.general', 'utils.datasets', 'utils.torch_utils','utils.plots', 'utils.augmentations', 'utils.metrics','models.common', 'models.yolo','importlib_resources.trees',],hookspath=[],hooksconfig={},runtime_hooks=[],excludes=[],win_no_prefer_redirects=False,win_private_assemblies=False,cipher=block_cipher,noarchive=False,
)# 2. 二进制文件处理(如 PyTorch 模型)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)# 3. 生成 EXE 的配置
exe = EXE(pyz,a.scripts,[],exclude_binaries=True,name='AI训练与验证', # 生成的 EXE 名称debug=False,bootloader_ignore_signals=False,strip=False,upx=True, # 压缩 EXE(可选)console=False, # 隐藏命令行窗口(GUI 用 False)disable_windowed_traceback=False,target_arch=None,codesign_identity=None,entitlements_file=None,
)# 4. 合并所有依赖(可选,单文件模式需启用)
coll = COLLECT(exe,a.binaries,a.zipfiles,a.datas,strip=False,upx=True,upx_exclude=[],name='AI训练与验证',
)
处理资源文件
对于需要包含的图片等资源:
pyinstaller --add-data "assets/*;assets/" main.py
解决常见打包问题
- 缺失依赖处理:
pyinstaller --hidden-import PySide6.QtXml main.py
- 图标设置:
pyinstaller --icon=app.ico main.py
- 减小体积:
pyinstaller --exclude-module tkinter main.py
部署注意事项
- Windows平台建议使用NSIS或Inno Setup创建安装程序
- macOS需要处理签名和公证流程
- Linux系统需注意动态库依赖关系
高级功能扩展
- 多语言支持:
from PySide6.QtCore import QTranslatortranslator = QTranslator()
translator.load("zh_CN.qm")
app.installTranslator(translator)
- 线程处理:
from PySide6.QtCore import QThread, Signalclass Worker(QThread):finished = Signal(str)def run(self):# 耗时操作self.finished.emit("任务完成")
性能优化建议
- 使用
QPixmapCache
缓存图像资源 - 复杂界面采用延迟加载策略
- 避免在主线程执行耗时操作
调试技巧
- 使用
QDebug
输出日志信息 - 通过
QMessageBox
进行关键节点提示 - 利用
pdb
设置断点调试
版本兼容性处理
- 在
requirements.txt
中固定版本:
PySide6==6.5.1
- 检查Qt特性可用性:
if hasattr(PySide6.QtCore, "QOperatingSystemVersion"):# 使用新版本API