def loadUiType(uiFilepath): import xml.etree.ElementTree as xml from cStringIO import StringIO # load a .ui file in memory parsed = xml.parse(uiFilepath) form_class_name = parsed.find('class').text base_class_name = parsed.find('widget').get('class') # convert the UI file into Python code o = StringIO() with open(uiFilepath, 'r') as f: compileUi(f, o, indent=0) # copy over some variables so any import commands are in the correct context frame = {} for v in ['__file__', '__name__', '__package__']: frame[v] = eval(v) # byte compile and execute the Python code exec(compile(o.getvalue(), '<string>', 'exec')) in frame # Fetch the base_class and form class based on their type # in the xml from designer form_class = frame['Ui_%s' % form_class_name] base_class = eval(base_class_name) return base_class, form_class
def ui_to_py(ui_file): ''' << ui_to_py(ui_file, py_file_name) >> convert *.ui to *.py to te same folder ''' if not os.path.isfile(ui_file): msg = 'no such file' print(msg) return msg py_file_name = os.path.splitext(ui_file)[0] + '.py' with open(py_file_name, 'w') as py_file: try: pyside2uic.compileUi(ui_file, py_file) print('{0} converted to {1}.'.format(ui_file.upper(), py_file_name.upper())) except Exception as e: print('Error: compilation error.', e) bakFileName = py_file_name.replace(".py", "_backup.py") # convert to cross compatible code subprocess.call([INTERPRETER_PATH, '-m', 'Qt', '--convert', py_file_name]) if (os.path.isfile(bakFileName)): os.remove(bakFileName) print("REMOVING", bakFileName)
def loadUiType(uiFile): """ Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text print 'widget=' + widget_class print 'form=' + form_class with open(uiFile, 'r') as f: o = StringIO() frame = {} pyside2uic.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 form_class = frame['Ui_%s' % form_class] print 'form=' + str(form_class) #base_class = getattr(QtGui, widget_class) base_class = eval('QtWidgets.%s' % widget_class) print 'widget=' + str(base_class) return form_class, base_class
def compile_ui(ui_file, py_file): """ Compiles a Py. file from Qt Designer .ui file :param ui_file: str :param py_file: str :return: """ if not QT_AVAILABLE: LOGGER.warning(QT_ERROR_MESSAGE) return if not PYSIDEUIC_AVAILABLE: LOGGER.warning( 'pysideuic is not available. UI compilation functionality is not available!' ) return if not os.path.isfile(ui_file): LOGGER.warning('UI file "{}" does not exists!'.format(ui_file)) return if os.path.isfile(ui_file): f = open(py_file, 'w') pysideuic.compileUi(ui_file, f, False, 4, False) f.close()
def ui2py(filePath=None, *args): """Convert qtDesigner .ui files to .py""" if not filePath: startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2(dialogStyle=2, fileMode=1, startingDirectory=startDir, fileFilter='PyQt Designer (*%s)' % UI_EXT, okc="Compile to .py") if not filePath: return False filePath = filePath[0] if not filePath: return False if not filePath.endswith(UI_EXT): filePath += UI_EXT compiledFilePath = filePath[:-2] + "py" pyfile = open(compiledFilePath, 'w') compileUi(filePath, pyfile, False, 4, False) pyfile.close() info = "PyQt Designer file compiled to .py in: " pm.displayInfo(info + compiledFilePath)
def convert_qt_ui(): from pyside2uic import compileUi rcc_path = find_qt_rcc() path = os.path.join(MYPATH, 'joulescope_ui') ignore_filename = os.path.join(path, '.gitignore') with open(ignore_filename, 'wt') as ignore: ignore.write('# Automatically generated. DO NOT EDIT\n') for source in os.listdir(path): source_base, ext = os.path.splitext(source) if ext == '.ui': target = source_base + '.py' with open(os.path.join(path, source), 'rt', encoding='utf8') as fsource: with open(os.path.join(path, target), 'wt', encoding='utf8') as ftarget: compileUi(fsource, ftarget, execute=False, indent=4, from_imports=True) elif ext == '.qrc': target = source_base + '_rc.py' rc = subprocess.run([ rcc_path, os.path.join(path, source), '-o', os.path.join(path, target) ]) if rc.returncode: raise RuntimeError('failed on .qrc file') else: continue ignore.write('%s\n' % target)
def loadUiType(uiFile): """ Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ # import pysideuic if Qt.IsPySide2: import pyside2uic as pysideuic elif Qt.IsPySide: import pysideuic # parse the uifie parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, '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 form_class = frame['Ui_%s' % form_class] base_class = eval('QtWidgets.%s' % widget_class) return form_class, base_class
def loadUi(uifile, widget): """ Load .ui file into widget @param uifile: filename @type uifile: str @type widget: QtWidgets.QWidget """ if PYQT_NAME.startswith('PyQt'): m = __import__(PYQT_NAME + '.uic') return m.uic.loadUi(uifile, widget) elif PYQT_NAME == 'PySide2': import pyside2uic as pysideuic else: import pysideuic import io stream = io.StringIO() pysideuic.compileUi(uifile, stream) ns_locals = {} exec(stream.getvalue(), None, ns_locals) if 'Ui_Form' in ns_locals: form = ns_locals['Ui_Form']() else: form = ns_locals['Ui_Dialog']() form.setupUi(widget) return form
def loadUiType(fileVar, subFolder="ui", uiName=None): """ To use this, pass the path to a UI file, and capture the output as FormClass and BaseClass. Define your class inheriting from both and call self.setupUi(self) in the __init__ """ uiFolder, filename = os.path.split(fileVar) if uiName is None: uiName = os.path.splitext(filename)[0] if subFolder: uiFile = os.path.join(uiFolder, subFolder, uiName + ".ui") parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} uic.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 form_class = frame['Ui_{0}'.format(form_class)] try: base_class = eval('QtGui.{0}'.format(widget_class)) except: base_class = eval('QtWidgets.{0}'.format(widget_class)) return form_class, base_class
def loadUiType(uiFile): """ Pyside "loadUiType" command like PyQt4 has one, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ uiFile = os.path.join(DIR, uiFile) if not os.path.exists(uiFile) else uiFile parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} pyside2uic.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 form_class = frame['Ui_%s' % form_class] base_class = eval('%s' % widget_class) return form_class, base_class
def compile_ui(fdir, file_name): py_file_name = file_name.split(".")[0] + ".py" pyfile = open("{}/{}".format(fdir, py_file_name), 'w') compileUi("{}/{}".format(fdir, file_name), pyfile, False, 4, False) pyfile.close() from ncsc_ui import soundness_checker_ui as scui reload(scui)
def loadUIForPM(): checkToolDir = os.path.normpath(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))) checkToolDir = os.path.split(checkToolDir)[0] destination = checkToolDir + '/GUIforPM' + '/ui_MainWindowForPM.py' source = checkToolDir + '/Qt/UI/GUIforPM' + '/MainWindowForPM.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False) destination = checkToolDir + '/GUIforPM' + '/ui_DetailsWindowForPM.py' source = checkToolDir + '/Qt/UI/GUIforPM' + '/DetailsWindowForPM.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False) destination = checkToolDir + '/GUIforPM' + '/ui_LocationDialog.py' source = checkToolDir + '/Qt/UI/GUIforPM' + '/LocationDialog.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False) destination = checkToolDir + '/GUIforPM' + '/ui_CreateProjectDialog.py' source = checkToolDir + '/Qt/UI/GUIforPM' + '/CreateProjectDialog.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False) destination = checkToolDir + '/GUIforPM' + '/ui_DeletePorjectDialog.py' source = checkToolDir + '/Qt/UI/GUIforPM' + '/deleteProjectDialog.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False)
def load_ui_type(ui_file): """ Loads UI Designer file (.ui) and parse the file :param ui_file: str, path to the UI file """ if not QT_AVAILABLE: LOGGER.warning(QT_ERROR_MESSAGE) return None, None if not PYSIDEUIC_AVAILABLE: LOGGER.warning( 'pysideuic is not available. UI compilation functionality is not available!' ) return None, None parsed = ElementTree.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 form_class = frame['Ui_{}'.format(form_class)] base_class = eval('{}'.format(widget_class)) return form_class, base_class
def load_ui_type(uiFile): """Summary Args: uiFile (TYPE): Description Returns: TYPE: Description """ parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} uic.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 form_class = frame['Ui_%s' % form_class] base_class = eval('QtWidgets.%s' % widget_class) return form_class, base_class
def loadUiType(uiFile=None): """ :author: Jason Parks Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ if not uiFile: try: uiFile = getUserFiles("Qt Designer Files", ".ui")[0] except IndexError: print("Invalid File.") return parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} pyside2uic.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 form_class = frame['Ui_%s' % form_class] base_class = getattr(QtWidgets, widget_class) return form_class, base_class
def loadBudgetUI(): ui_dir = os.path.dirname(os.path.realpath( os.path.abspath(__file__))) + '\Qt\UI' desination = os.path.dirname(os.path.realpath(os.path.abspath(__file__))) source = ui_dir + '\polyCountBudget.ui' py_file = desination + '\ui_polyCountBudget.py' with open(py_file, 'w') as pyfile: compileUi(source, pyfile, False, 4, False) source = ui_dir + '\polyCountBudget2.ui' py_file = desination + '\ui_polyCountBudget2.py' with open(py_file, 'w') as pyfile: compileUi(source, pyfile, False, 4, False) source = ui_dir + '\\auditMainWindow.ui' py_file = desination + '\ui_auditMainWindow.py' with open(py_file, 'w') as pyfile: compileUi(source, pyfile, False, 4, False) source = ui_dir + '\polyCountBudget3.ui' py_file = desination + '\ui_polyCountBudget3.py' with open(py_file, 'w') as pyfile: compileUi(source, pyfile, False, 4, False) source = ui_dir + '\\addBudgetDialog.ui' py_file = desination + '\ui_addBudgetDialog.py' with open(py_file, 'w') as pyfile: compileUi(source, pyfile, False, 4, False)
def loadUi(uifile, widget): """ Load .ui file into widget @param uifile: filename @type uifile: str @type widget: QtWidgets.QWidget """ if PYQT_NAME.startswith('PyQt'): m = __import__(PYQT_NAME + '.uic') return m.uic.loadUi(uifile, widget) elif PYQT_NAME == 'PySide2': import pyside2uic as pysideuic else: import pysideuic import io stream = io.StringIO() pysideuic.compileUi(uifile, stream) ns_locals = {} exec(stream.getvalue(), None, ns_locals) if 'Ui_Form' in ns_locals: form = ns_locals['Ui_Form']() else: form = ns_locals['Ui_Dialog']() form.setupUi(widget) return form
def load_ui_types(uifile): """ Ripped from https://github.com/mottosso/Qt.py/blob/master/examples/loadUi/baseinstance2.py :param uifile: :return: """ import xml.etree.ElementTree as ElementTree from cStringIO import StringIO parsed = ElementTree.parse(uifile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uifile, 'r') as f: o = StringIO() frame = {} try: import pyside2uic as pysideuic except ImportError: import pysideuic as pysideuic 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 form_class = frame['Ui_%s' % form_class] base_class = eval('QtWidgets.%s' % widget_class) return form_class, base_class
def loadUiType(uiFile): ''' Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. ''' import pyside2uic import xml.etree.ElementTree as xml if sys.version_info[0] == 2: from cStringIO import StringIO else: from io import StringIO import PySide2.QtWidgets parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} pyside2uic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc, frame) #Fetch the base_class and form class based on their type in the xml from designer form_class = frame['Ui_%s' % form_class] base_class = eval('PySide2.QtWidgets.%s' % widget_class) return form_class, base_class
def ui2py(uifile): """""" pyfilename = '_'.join(uifile.rsplit('.', 1)) + '.py' with open(pyfilename, 'w') as pyfile: compileUi(uifile, pyfile) print('compile ui to py done -> %s' % pyfilename) return pyfilename
def ui2py(uifile): """""" if os.path.exists(uifile): outfile = '%s.py' % uifile.replace('.', '_') with open(outfile, 'w') as pyfile: compileUi(uifile, pyfile) print('%s to %s finished.' % (uifile, outfile)) else: print('uifile does not exists! <- %s' % uifile)
def main(): ui_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'ui')) for dir_path, _, files in os.walk(ui_path): for ui_file in [f for f in files if os.path.splitext(f)[1] == '.ui']: base = os.path.splitext(ui_file)[0] py_file = base + '_ui.py' if py_file in files: with open(os.path.join(dir_path, py_file), 'w') as pyfobj: compileUi(os.path.join(dir_path, ui_file), pyfobj) print('py_file recompiled:', py_file)
def loadUiType(uiFile=""): """ loadUiType [读取UI文件] [description] 根据python版本以及PyQt或者PySide的不同版本进行统一的ui文件读取 生成原理: 过去我们借助 uic 工具将Qt Designer生成的ui文件编译成Python文件进行调用 这个函数就是将这个步骤放到了代码中执行,生成的结果将会直接运行到内存中 兼容 Python3 & Python2 Keyword Arguments: uiFile {str} -- ui文件的路径 (default: {""}) Returns: base_class """ import pyside2uic as uic import xml.etree.ElementTree as xml # Note 兼容Python3 try: from cStringIO import StringIO except: from io import StringIO parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text # Note 兼容Python3 try: with open(uiFile, 'r') as f: o = StringIO() frame = {} uic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc) in frame form_class = frame['Ui_%s' % form_class] base_class = eval('%s' % widget_class) except: with open(uiFile, 'r', encoding="utf-8") as f: o = StringIO() frame = {} uic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc, frame) form_class = frame['Ui_%s' % form_class] base_class = eval('%s' % widget_class) return (base_class, form_class)
def _loadUiType(uiFile): """ PySide lacks a "loadUiType" command like PyQt4's, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. from stackoverflow: http://stackoverflow.com/a/14195313/3781327 seems like this might also be a legitimate solution, but I'm not sure how to make PyQt4 and pyside look the same... http://stackoverflow.com/a/8717832 """ pyside2uic = None if QT_LIB == PYSIDE2: try: import pyside2uic except ImportError: # later versions of pyside2 have dropped pyside2uic; use the uic binary instead. pyside2uic = None if pyside2uic is None: pyside2version = tuple(map(int, PySide2.__version__.split("."))) if (5, 14) <= pyside2version < (5, 14, 2, 2): warnings.warn( 'For UI compilation, it is recommended to upgrade to PySide >= 5.15' ) # get class names from ui file import xml.etree.ElementTree as xml parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text # convert ui file to python code if pyside2uic is None: uic_executable = QT_LIB.lower() + '-uic' uipy = subprocess.check_output([uic_executable, uiFile]) else: o = _StringIO() with open(uiFile, 'r') as f: pyside2uic.compileUi(f, o, indent=0) uipy = o.getvalue() # execute python code pyc = compile(uipy, '<string>', 'exec') frame = {} exec(pyc, frame) # fetch the base_class and form class based on their type in the xml from designer form_class = frame['Ui_%s' % form_class] base_class = eval('QtGui.%s' % widget_class) return form_class, base_class
def load(ui_file, base_instance=None): try: return Qt.QtCompat.loadUi(ui_file, base_instance) except Exception: # -- For applications such as 3dsmax we have to compile the # -- ui differently try: import pyside2uic as pyuic from cStringIO import StringIO except Exception: raise RuntimeError('No implementation for loadUi found.') # -- Read out the xml file xml_data = exml.parse(ui_file) # -- Get the lcass of the widget and the form widget_class = xml_data.find('widget').get('class') form_class = xml_data.find('class').text # -- Open the ui file as text with open(ui_file, 'r') as f: # -- Create a file like object o = StringIO() frame = {} # -- Compile the ui into compiled python and execute it pyuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') eval('exec pyc in frame') # -- Get the form class form_class = frame['Ui_%s' % form_class] # -- Alter what we're evaulating based on what version # -- of qt we're running try: base_class = eval('Qt.QtGui.%s' % widget_class) except (NameError, AttributeError): base_class = eval('Qt.QtWidgets.%s' % widget_class) # -- Subclass the loaded classes to build a wrapped widget class _WrappedHelper(form_class, base_class): # noinspection PyShadowingNames def __init__(self, parent=None): super(_WrappedHelper, self).__init__(parent) self.setupUi(self) return _WrappedHelper()
def loadUIForArtist(): checkToolDir = os.path.normpath( os.path.dirname(os.path.realpath(os.path.abspath(__file__)))) checkToolDir = os.path.split(checkToolDir)[0] destination = checkToolDir + '/GUIforArtist' + '/ui_MainWindowForArtist.py' source = checkToolDir + '/Qt/UI/GUIforArtist' + '/MainWindowForArtist.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False) destination = checkToolDir + '/GUIforArtist' + '/ui_ChooseLocationDialog.py' source = checkToolDir + '/Qt/UI/GUIforArtist' + '/ChooseLocationDialog.ui' with open(destination, 'w') as f: compileUi(source, f, False, 4, False)
def _compile_ui_file(*args): import sys, pprint from pyside2uic import compileUi py_file = pm.textFieldButtonGrp(py_store_path_field, q=True, text=True) ui_file = pm.textFieldButtonGrp(ui_file_location_field, q=True, text=True) output_file = open(py_file, 'w') compileUi(ui_file, output_file, False, 4, False) output_file.close() print("Compile Done!") return True
def loadUiType(uiFile): parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, '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 form_class = frame['Ui_%s' % form_class] base_class = getattr(QtWidgets, widget_class) return form_class, base_class
def convertFile(self, *args): if self.filePathName is not None and self.textInput.getText() != '': import sys, pprint from pyside2uic import compileUi drive, path = os.path.splitdrive(self.filePathName) path, filename = os.path.split(path) outFilePath = drive + path + "/" + self.textInput.getText() #print ("%s , %s , %s" % (drive,path,filename)) pyfile = open(outFilePath, 'w') compileUi(self.filePathName, pyfile, False, 4, False) pyfile.close() elif self.textInput.getText() == '': print "No output Filename" else: print "No File Selected"
def _generate(self): """ Generate the Python code. """ if sys.hexversion >= 0x03000000: if self._opts.output == '-': from io import TextIOWrapper pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8') else: pyfile = open(self._opts.output, 'wt', encoding='utf8') else: if self._opts.output == '-': pyfile = sys.stdout else: pyfile = open(self._opts.output, 'wt') compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent, self._opts.from_imports)
def load_ui_type(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 = {} pyside2uic.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 design form_class = frame['Ui_{0}'.format(form_class)] base_class = eval('QtWidgets.{0}'.format(widget_class)) return form_class, base_class
def _generate(self): """ Generate the Python code. """ if sys.hexversion >= 0x03000000: if self._opts.output == '-': from io import TextIOWrapper pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8') else: pyfile = open(self._opts.output, 'wt', encoding='utf8') else: if self._opts.output == '-': pyfile = sys.stdout else: pyfile = open(self._opts.output, 'wt') compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent, self._opts.from_imports)
def check_ui_module(module): if not a2core.is_dev_mode(): return if getattr(sys, 'frozen', False): # log.info('frozen! no need to compile %s' % module) return pyfile = module.__file__ folder, pybase = os.path.split(pyfile) uiname = os.path.splitext(pybase)[0] uibase = None if uiname.endswith(UI_FILE_SUFFIX): uibase = uiname[:-len(UI_FILE_SUFFIX)] + '.ui' else: with open(pyfile, 'r') as fobj: line = fobj.readline() while line and uibase is not None: line = line.strip() if line.startswith('# Form implementation '): uibase = line[line.rfind("'", 0, -1) + 1:-1] uibase = os.path.basename(uibase.strip()) log.debug('checkUiModule from read: %s' % uibase) line = fobj.readline() if uibase is None: raise RuntimeError('Could not get source ui file from module:\n %s\n ' 'Not a ui file module??!' % module) uifile = os.path.join(folder, uibase) if not uibase or not os.path.isfile(uifile): # Nothing to test against. That's alright! # log.debug('Ui-file not found: %s' % pybase) return py_time = os.path.getmtime(pyfile) ui_time = os.path.getmtime(uifile) diff = py_time - ui_time if diff < 0: log.debug('%s needs compile! (age: %is)' % (pybase, diff)) with open(pyfile, 'w') as pyfobj: compileUi(uifile, pyfobj) reload(module)
def loadUiType(uiFile): """ Pyside "loadUiType" command like PyQt4 has one, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = StringIO() frame = {} uic.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 form_class = frame['Ui_%s'%form_class] base_class = eval('QtWidgets.%s'%widget_class) return base_class, form_class
def loadUiType(uiFile): """ Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. http://tech-artists.org/forum/showthread.php?3035-PySide-in-Maya-2013 """ parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, '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 print form_class + ' - ' + widget_class form_class = frame['Ui_%s'%form_class] base_class = eval('QtWidgets.%s'%widget_class) return form_class, base_class
def ui2py(uifile): pyfilename = '_'.join(uifile.rsplit('.', 1)) + '.py' with open(pyfilename, 'w') as pyfile: compileUi(uifile, pyfile)