首页 > 解决方案 > 如何在 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 。

标签: pythonpyqtpyqt5

解决方案


我使用下面的脚本来自动生成 .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)

推荐阅读