Search code examples
pythonqt5qt-designersignals-slotspython-3.10

Connecting a Qt5 Designer design with a slot function in my main() code without modifying the Designer file


Being new in using Qt5 and Object Oriented Programming, I try to use the Designer for the design of my GUI.

I have foreseen a button that calls a custom slot once clicked. In Qt5 Designer I used a custom slot automatically set to slot1(). I save the design into an .ui file and I run pyuic5 in order to obtain a .py file for my GUI.

This .py file I can run but it gives me an AttributeError stating that the object 'Ui_HomeWindow' has no attribute 'slot1'.

This is as I expected because I did not provide the slot1 function in the class. From Designer I understand that the .py file obtained after running pyuic5 should not be modified (fully understandable).

I need to define the slot1 function in, let say, my main() so that it gets accepted as a method of the class as generated by Designer.

Having read a lot about polymorphism and inheritance I get completely lost (I am new in OOP).

Inheriting from the class defined by Designer after running pyuic5 will allow me to reuse methods in another class defined by myself. In that class I can then define the slot1 function. Where I get stuck is that by clicking a button, the "Designer" generated class needs access to the slot1 function defined in my class. Translated in OOP concepts, the parent class (resulting from Designer) needs to access a function defined in a child class (defined by me).

Is this correct? Is this possible, and how can I make this happen? Could someone point me to a simple explanation please? What I read was always sophisticated and complex, while I cannot believe that one needs to be a guru in OOP for being able to use Qt5 Designer. Thank you very much in advance for the hints.


Solution

  • I suggest you use the clicked method, and connect the button to a method in your class, like this:

    from ui_main import Ui_MainWindow
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, app, force_quit=False):
            QtWidgets.QMainWindow.__init__(self)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self) 
            self.ui.pushButton_export.clicked.connect(self.export)
    
        def export(self):
            ...
    

    So, I created a ui_main.py file using designer which contains the Ui_MainWindow class, which contains a button that I named export. This remains unchanged but is inherited by your MainWindow class that you develop with all the methods you need.