PyQt qrc2py 使用PowerShell将qrc文件转为py文件并且将导入模块PyQt或PySide转换为qtpy模块开箱即用

前言

由于需要使用不同的qt环境(PySide,PyQt)所以写了这个脚本,使用找到的随便一个rcc命令去转换qrc文件,然后将导入模块换成qtpy这个通用库(支持pyside2-6,pyqt5-6),老版本的是Qt.py(支持pyside0-2~pyqt4-5)你可以自己改。

使用

上一篇文章写了如何将ui转为py 链接 这一篇换个写法

因为qrc文件一般只有一个,不像ui文件有很多个,所以在这里直接指定文件,不去查询所有的qrc文件

powershell 复制代码
# .LINK https://blog.csdn.net/weixin_42579717/article/details/137281606
# 检查rcc命令是否存在
$_commands = @("pyrcc5", "pyside2-rcc", "pyrcc6", "pyside6-rcc", "pyside-rcc", "pyrcc")
$command = $null
foreach ($cmd in $_commands)
{
    $command = Get-Command $cmd -ErrorAction SilentlyContinue
    if ($command)
    {
        break
    }
}
if (-not$command)
{
    Write-Host "Command not found."
    exit 1
}
$command = $command.Name
Write-Output "Use command: $command"

# 获取当前脚本所在的文件夹
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition

$qrcFile = Join-Path $scriptDirectory "resource.qrc"
$pyFile = Join-Path $scriptDirectory "resource_rc.py"

Write-Host $qrcFile
Write-Host $pyFile
& $command -o $pyFile $qrcFile
# 检查文件转换是否成功
if (Test-Path $pyFile)
{
    # 更换导入模块
    (Get-Content $pyFile -Encoding UTF8) -replace "from (PyQt[456]?|PySide[26]?)", "from qtpy" | Set-Content $pyFile -Encoding UTF8
    Write-Host "Files have been converted and modified successfully: $pyFile"
}
else
{
    Write-Host "convert failed: $qrcFile"
}

如果你的项目有结构的话比如下图

可以将以下代码替换

powershell 复制代码
# 获取当前脚本所在的文件夹
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition
$parentDirectory = Split-Path -Parent $scriptDirectory

$qrcFile = Join-Path $scriptDirectory "resource.qrc"
$pyFile = Join-Path $parentDirectory "ui/resource_rc.py"

PS

补充说明,PowerShell 不能用中文文档注释但是可以单行注释

相关推荐
Humbunklung10 小时前
PySide6 GUI 学习笔记——常用类及控件使用方法(多行文本控件QTextEdit)
笔记·python·学习·pyqt
En^_^Joy2 天前
PyQt常用控件的使用:QFileDialog、QMessageBox、QTreeWidget、QRadioButton等
开发语言·python·pyqt
zhlei_123452 天前
封闭内网安装配置VSCode Anconda3 并配置 PyQt5开发
ide·vscode·pyqt
猫头虎3 天前
零基础安装 Python 教程:从下载到环境配置一步到位(支持 VSCode 和 PyCharm)与常用操作系统操作指南
vscode·python·pycharm·beautifulsoup·numpy·pyqt·pip
江畔柳前堤11 天前
PyQt学习系列08-插件系统与模块化开发
运维·开发语言·数据库·python·学习·机器学习·pyqt
江畔柳前堤14 天前
PyQt学习系列05-图形渲染与OpenGL集成
开发语言·javascript·人工智能·python·学习·ecmascript·pyqt
江畔柳前堤14 天前
PyQt学习系列11-综合项目:多语言文件管理器
开发语言·网络·python·学习·django·pyqt
幽络源小助理15 天前
基于Yolov8+PyQT的老人摔倒识别系统源码
yolo·pyqt
江畔柳前堤15 天前
PyQt学习系列07-数据库操作与ORM集成
数据库·学习·算法·机器学习·架构·pyqt
江畔柳前堤16 天前
PyQt学习系列10-性能优化与调试技巧
开发语言·javascript·数据库·学习·性能优化·ecmascript·pyqt