compile_ui.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # Copyright (c) 2023 Riverbank Computing Limited.
  2. # Copyright (c) 2006 Thorsten Marek.
  3. # All right reserved.
  4. #
  5. # This file is part of PyQt.
  6. #
  7. # You may use this file under the terms of the GPL v3 or the revised BSD
  8. # license as follows:
  9. #
  10. # "Redistribution and use in source and binary forms, with or without
  11. # modification, are permitted provided that the following conditions are
  12. # met:
  13. # * Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # * Redistributions in binary form must reproduce the above copyright
  16. # notice, this list of conditions and the following disclaimer in
  17. # the documentation and/or other materials provided with the
  18. # distribution.
  19. # * Neither the name of the Riverbank Computing Limited nor the names
  20. # of its contributors may be used to endorse or promote products
  21. # derived from this software without specific prior written
  22. # permission.
  23. #
  24. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  27. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  28. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  29. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  30. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  31. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  32. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  35. from .Compiler import indenter, compiler
  36. _header = """# Form implementation generated from reading ui file '{}'
  37. #
  38. # Created by: PyQt6 UI code generator {}
  39. #
  40. # WARNING: Any manual changes made to this file will be lost when pyuic6 is
  41. # run again. Do not edit this file unless you know what you are doing.
  42. """
  43. _display_code = """
  44. if __name__ == "__main__":
  45. import sys
  46. app = QtWidgets.QApplication(sys.argv)
  47. %(widgetname)s = QtWidgets.%(baseclass)s()
  48. ui = %(uiclass)s()
  49. ui.setupUi(%(widgetname)s)
  50. %(widgetname)s.show()
  51. sys.exit(app.exec())"""
  52. def compileUiDir(dir, recurse=False, map=None, max_workers=0, **compileUi_args):
  53. """compileUiDir(dir, recurse=False, map=None, **compileUi_args)
  54. Creates Python modules from Qt Designer .ui files in a directory or
  55. directory tree.
  56. dir is the name of the directory to scan for files whose name ends with
  57. '.ui'. By default the generated Python module is created in the same
  58. directory ending with '.py'.
  59. recurse is set if any sub-directories should be scanned. The default is
  60. False.
  61. map is an optional callable that is passed the name of the directory
  62. containing the '.ui' file and the name of the Python module that will be
  63. created. The callable should return a tuple of the name of the directory
  64. in which the Python module will be created and the (possibly modified)
  65. name of the module. The default is None.
  66. max_workers is the maximum number of worker processes to use. A value of 0
  67. means only the current process is used. A value of None means that the
  68. number of processors on the machine is used.
  69. compileUi_args are any additional keyword arguments that are passed to
  70. the compileUi() function that is called to create each Python module.
  71. """
  72. from functools import partial
  73. import os
  74. jobs = []
  75. # Add a compilation job.
  76. def add_job(ui_dir, ui_file):
  77. # Ignore if it doesn't seem to be a .ui file.
  78. if ui_file.endswith('.ui'):
  79. py_dir = ui_dir
  80. py_file = ui_file[:-3] + '.py'
  81. # Allow the caller to change the name of the .py file or generate
  82. # it in a different directory.
  83. if map is not None:
  84. py_dir, py_file = map(py_dir, py_file)
  85. ui_path = os.path.join(ui_dir, ui_file)
  86. jobs.append((ui_path, py_dir, py_file))
  87. if recurse:
  88. for root, _, files in os.walk(dir):
  89. for ui in files:
  90. add_job(root, ui)
  91. else:
  92. for ui in os.listdir(dir):
  93. if os.path.isfile(os.path.join(dir, ui)):
  94. add_job(dir, ui)
  95. if jobs and max_workers != 0:
  96. from concurrent.futures import ProcessPoolExecutor
  97. with ProcessPoolExecutor(max_workers=max_workers) as executor:
  98. executor.map(partial(_run_job, **compileUi_args), jobs)
  99. else:
  100. for job in jobs:
  101. _run_job(job, **compileUi_args)
  102. def _run_job(job, **compileUi_args):
  103. """ Run a job to compile a single .ui file. """
  104. import os
  105. ui_path, py_dir, py_file = job
  106. # Make sure the destination directory exists.
  107. try:
  108. os.makedirs(py_dir)
  109. except:
  110. pass
  111. py_path = os.path.join(py_dir, py_file)
  112. with open(py_path, 'w', encoding='utf-8') as py_f:
  113. compileUi(ui_path, py_f, **compileUi_args)
  114. def compileUi(uifile, pyfile, execute=False, indent=4):
  115. """compileUi(uifile, pyfile, execute=False, indent=4)
  116. Creates a Python module from a Qt Designer .ui file.
  117. uifile is a file name or file-like object containing the .ui file.
  118. pyfile is the file-like object to which the Python code will be written to.
  119. execute is optionally set to generate extra Python code that allows the
  120. code to be run as a standalone application. The default is False.
  121. indent is the optional indentation width using spaces. If it is 0 then a
  122. tab is used. The default is 4.
  123. """
  124. from PyQt6.QtCore import PYQT_VERSION_STR
  125. try:
  126. uifname = uifile.name
  127. except AttributeError:
  128. uifname = uifile
  129. indenter.indentwidth = indent
  130. pyfile.write(_header.format(uifname, PYQT_VERSION_STR))
  131. winfo = compiler.UICompiler().compileUi(uifile, pyfile)
  132. if execute:
  133. indenter.write_code(_display_code % winfo)