Search code examples
pythonpyqtpyqt4qtgui

Converting pyqt ui files into py files


So I've recently switched to pyqt from tkinter for my python gui apps, and I love it 😊.

However there is one thing that bugs me and I hope you guys can help me.

I like using the qtdesigner tool so I can rapidly develop interfaces, but when I convert the qui to py, it constructs a class in a slightly unsual way with the setupUi method that setups the main window. I was hoping I could change the way it made the class into a more conventional way with an init method so that I could inherit from it and define my events etc from in another file. At the moment I manually do it. This would make it easy to modify the ui in designer and still import from the converted py file without having to make any mods.

I hope my question makes sense, and I am looking forward to hear how other developers out there handle this.

Thanks in advance


Solution

  • I normally load ui file itself without converting to py. That actually save some time and code also looks nice. Here is a snippet

    from PyQt4 import QtGui, QtCore, uic
    import sys
    
    # Here you can add your ui path from desigener, no need to convert
    RESOURCE_PATH             = package.__BASERESLOC__
    baseUI                    = os.path.join(RESOURCE_PATH, "base_main.ui")
    baseUIClass, baseUIWidget = uic.loadUiType(baseUI)
    
    class BASEGUICLS(baseUIWidget, baseUIClass):
        def __init__(self,parent=None):
            super(BASEGUICLS, self).__init__(parent)
            self.setupUi(self)
            #after this you will have everything
            self.pushButton.setText("Foo")
    
    def main():
        """
        Main function which init main GUI.
        """
        app = QtGui.QApplication(sys.argv)
        ex = BASEGUICLS(None)
        ex.show()
        sys.exit(app.exec_())