Last active
December 17, 2018 10:08
-
-
Save PaulSchweizer/d34e92e0a246558a0f36 to your computer and use it in GitHub Desktop.
PySide UI
This file contains hidden or 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 as xml | |
| from cStringIO import StringIO | |
| try: | |
| import pysideuic | |
| except: | |
| import pysideuic2 as pysideuic | |
| from Qt import QtWidgets | |
| def ui_class(ui_file): | |
| """Build a class from a designer .ui file.""" | |
| b, f = _load_ui_type(ui_file) | |
| class BaseUi(b, f): | |
| def __init__(self, parent=None): | |
| super(BaseUi, self).__init__(parent=parent) | |
| self.setupUi(self) | |
| return BaseUi | |
| def _load_ui_type(ui_file): | |
| """Load a ui file for PySide. | |
| PySide lacks the "_load_ui_type" command, so we have to convert | |
| the UI file to python code in-memory first and then execute it in a | |
| special frame to retrieve the form_class. | |
| Args: | |
| ui_file (str): The .ui file. | |
| Returns: | |
| The base and form class, derived from the .ui file. | |
| """ | |
| parsed = xml.parse(ui_file) | |
| widget_class = parsed.find('widget').get('class') | |
| form_class = parsed.find('class').text | |
| with open(ui_file, 'r') as f: | |
| o = StringIO() | |
| frame = {} | |
| pysideuic.compileUi(f, o, indent=0) | |
| pyc = compile(o.getvalue(), '<string>', 'exec') | |
| exec pyc in frame | |
| # Fetch the base_class and form_class based on their type | |
| # in the xml from designer | |
| base_class = getattr(QtWidgets, widget_class) | |
| form_class = frame['Ui_%s' % form_class] | |
| return base_class, form_class | |
| ui_file = "YOUR UI FILE PATH!!" | |
| class WidgetFromUiFile(ui_class(ui_file)): | |
| def __init__(self, parent=None): | |
| """Setup the tray icon and signals.""" | |
| super(WidgetFromUiFile, self).__init__(parent=parent) | |
| if __name__ == "__main__": | |
| w = WidgetFromUiFile() | |
| w.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment