Advertisement
stuppid_bot

PyQt5 compile .ui and .qrc files into python modules

Jan 23rd, 2016
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.87 KB | None | 0 0
  1. import os
  2. import re
  3.  
  4.  
  5. MODULE_TEMPLATE = """from PyQt5.QtWidgets import QApplication, {base}
  6. from {ui_module} import Ui_{cls}
  7.  
  8.  
  9. class {cls}({base}):
  10.    def __init__(self, parent=None):
  11.        super({base}, self).__init__(parent)
  12.        self.ui = Ui_{cls}()
  13.        self.ui.setupUi(self)
  14.  
  15.  
  16. if __name__ == '__main__':
  17.    import sys
  18.  
  19.    app = QApplication(sys.argv)
  20.    w = {cls}()
  21.    w.show()
  22.  
  23.    sys.exit(app.exec_())
  24. """
  25. CLASS_RE = re.compile('<class>([^<]+)')
  26. # У сгенерированного ui файла у <widget/> есть параметр name, его значение
  27. # совпадает с <class>CLASS_NAME</class>, но при генерации скрипта pyuic5.exe
  28. # использует содержимое <class/>
  29. BASE_RE = re.compile('<widget class="([^"]+)')
  30.  
  31.  
  32. def compile_qt(path='.'):
  33.     """Данная функция рекурсивно проходит по всем каталогам начиная с
  34.    указанного и ищет файлы с расширениями .ui и .qrc, а затем компилирует их
  35.    в python модули. Помимо этого создается модуль для тестирования."""
  36.     for cur_path, dirs, files in os.walk(path):
  37.         full_path = os.path.realpath(cur_path)
  38.         # print("cd", full_path)
  39.         os.chdir(full_path)
  40.         for filename in files:
  41.             # print(os.path.join(cur_path, filename))
  42.             if filename[-3:].lower() == '.ui':
  43.                 ui_filename = 'ui_' + filename[:-3] + '.py'
  44.                 if os.path.exists(ui_filename):
  45.                     continue
  46.                 cmd = 'pyuic5 {} -o {}'.format(
  47.                         filename, ui_filename)
  48.                 # print(cmd)
  49.                 os.system(cmd)
  50.                 test_filename = filename[:-3] + '.py'
  51.                 # Придется удалять ui_foo.py и foo.py
  52.                 if os.path.exists(test_filename):
  53.                     continue
  54.                 # Создаем модуль для теста
  55.                 with open(filename, encoding='utf-8') as fp:
  56.                     content = fp.read()
  57.                 cls = CLASS_RE.search(content).group(1)
  58.                 base = BASE_RE.search(content).group(1)
  59.                 with open(test_filename, 'w', encoding='utf-8') as fp:
  60.                     fp.write(MODULE_TEMPLATE.format(
  61.                         cls=cls, base=base, ui_module=ui_filename[:-3]))
  62.             elif filename[-4:].lower() == '.qrc':
  63.                 rc_filename = filename[:-4] + '_rc.py'
  64.                 if os.path.exists(rc_filename):
  65.                     continue
  66.                 cmd = 'pyrcc5 {} -o {}'.format(
  67.                     filename, rc_filename)
  68.                 # print(cmd)
  69.                 os.system(cmd)
  70.  
  71.  
  72. if __name__ == '__main__':
  73.     import sys
  74.     sys.exit(compile_qt())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement