python - 如何在 Mac 上将 .ui 文件转换为 .py 文件?
问题描述
如何将 QT Creator 生成的 .ui 文件转换为 .py 文件?
我曾经在 Windows 上使用 .bat 文件将 .ui 文件转换为 .py 文件:
@echo off
for %%f in (*.ui) do (
`echo %%f`
`C:\Python34\Lib\site-packages\PyQt5\pyuic5.bat -x %%f -o %%`[`~nf.py`](https://~nf.py)
)
pause
我现在无法再使用 PC 进行转换(而且我已经厌倦了仅仅为了转换文件而切换计算机),所以我需要能够在 mac OS 中将 .ui 文件转换为 .py 。
解决方案
我使用下面的脚本来自动生成 .ui 文件和资源,它应该适用于任何操作系统。
只需设置input_path
为包含您的 ui 文件output_path
的文件夹和您希望生成 Python 文件的文件夹:
请注意,为了额外的安全性,脚本将检查 .ui 文件是否以 qtcreator 添加的注释开头:“在此文件中所做的所有更改都将丢失”。
# Use this script to convert Qt Creator UI and resource files to python
import os
import subprocess
input_path = os.path.join(os.path.dirname(__file__), 'resources', 'qt')
output_path = os.path.join(os.path.dirname(__file__), 'src', 'widgets')
def check_file(file):
if 'All changes made in this file will be lost' in open(file).read():
return True
return False
for f in os.listdir(input_path):
if not os.path.isfile(f):
pass
file_name, extension = os.path.splitext(f)
if extension == '.ui':
input_file = os.path.join(input_path, f)
output_file = os.path.join(output_path, file_name + '.py')
if os.path.isfile(output_file):
if not check_file(output_file):
print('Warning: tried to overwrite a file generated outside Qt Creator. {}'.format(output_file))
continue
subprocess.call('pyuic5 --import-from=widgets -x {} -o {}'.format(input_file, output_file), shell=True)
elif extension == '.qrc':
input_file = os.path.join(input_path, f)
output_file = os.path.join(output_path, file_name + '_rc.py')
if os.path.isfile(output_file):
if not check_file(output_file):
print('Warning: tried to overwrite a file generated outside Qt Creator. {}'.format(output_file))
continue
subprocess.call('pyrcc5 {} -o {}'.format(input_file, output_file), shell=True)
推荐阅读
- javascript - Selectpicker 不能与表单转发器一起使用
- apache-spark - Pyspark、groupBy 和嵌套列前缀
- r - 确保 R 中的因子水平相同
- excel - 将 txt 文件导入单个工作表并在第 1 列中添加文件名
- reactjs - ReactJS:AG-GRID:基于元数据动态分配单元格编辑器
- linux - 将多个变量从 Bash 脚本传递到 Expect 脚本
- c# - 有没有办法在 C# WinForms 应用程序中打印或传输 DataGridView 的结果?
- pine-script - 使用多个时间框架来绘制购买或出售
- python - 来自具有不同长度的数组的数据帧 - 通过行的 rmean 填充缺失值
- c++ - switch 语句和对象隐式 int 转换