Created
March 7, 2023 14:52
-
-
Save aminechraibi/eb4f8d340df31b2c8beb5ae6f4eaf3b3 to your computer and use it in GitHub Desktop.
Learn how to generate a Python file for a UI file created in Qt Designer using PyQt5, the popular Python GUI framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import xml.etree.ElementTree | |
def to_camel_case(string): | |
words = string.split('_') | |
return ''.join([word.capitalize() for word in words]) | |
def generate_py(file): | |
stub = '' | |
root = xml.etree.ElementTree.parse(file).getroot() | |
stub += ' def __stubs(self):\n' | |
stub += ' """ This just enables code completion. It should never be called """\n' | |
widgets = [] | |
for widget in root.findall('.//widget'): | |
name = widget.get('name') | |
if len(name) > 3: | |
cls = widget.get('class') | |
stub += f' self.{name} = {cls}()\n' | |
widgets.append({ | |
'name': name, | |
'class': cls | |
}) | |
stub += ' raise AssertionError("This should never be called")\n\n' | |
classes = [b['class'] for b in widgets] | |
buttons_names = [b['name'] for b in widgets if b['class'] == 'QPushButton'] | |
imports = 'from PyQt5 import uic\n' | |
imports += 'from PyQt5.QtWidgets import QApplication, ' + ', '.join(classes) + '\n\n' | |
file_name_ext = os.path.basename(file) | |
file_name, file_extension = os.path.splitext(file_name_ext) | |
code = imports | |
code += """def connect(component, action): | |
component.clicked.disconnect() | |
component.clicked.connect(action)\n\n""" | |
app_name = f'{to_camel_case(file_name)}App' | |
code += f'Ui_MainWindow, QtBaseClass = uic.loadUiType("{file_name_ext}")\n\n' | |
code += f'class {app_name}(QMainWindow, Ui_MainWindow):\n\n' | |
code += stub | |
code += """ def __init__(self): | |
super().__init__() | |
self.setupUi(self)\n\n""" | |
for button in buttons_names: | |
code += f' connect(self.{button}, self.on_{button}_clicked)\n' | |
code += '\n' | |
for button in buttons_names: | |
code += f""" def on_{button}_clicked(self): | |
print('on_{button}_clicked')\n\n""" | |
code += f"""\nif __name__ == "__main__": | |
app = QApplication([]) | |
window = {app_name}() | |
window.show() | |
app.exec_() | |
""" | |
return code, file_name | |
def main(): | |
# UI file created in Qt Designer | |
ui_file = "gui.ui" | |
code, file_name = generate_py(ui_file) | |
with open(f'{file_name}_app.py', 'w') as f: | |
f.write(code) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment