Python code generation with pyside-uic

前端 未结 8 1119
野的像风
野的像风 2020-12-01 12:18

How can I generate python code from a QtDesigner file ? I found pyside-uic but I can\'t find an example for the syntax. I run win7 and pythonxy with spyder.

8条回答
  •  攒了一身酷
    2020-12-01 13:05

    import pysideuic
    import xml.etree.ElementTree as xml
    from cStringIO import StringIO
    
    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 = {}
    
            pysideuic.compileUi(f, o, indent=0)
            pyc = compile(o.getvalue(), '', '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('QtGui.%s'%widget_class)
    
        return form_class, base_class
    

    You can use this way to load the UI and can also get form_class as well as the base class as return type... but if you do not want to convert, otherwise Yes the following is the correct way.

    pyside-uic.exe MyWindow.ui -o MyWindow.py
    

提交回复
热议问题