Search code examples
pythonqtpyqt5qt-designer

How to bind a function to an Action from Qt menubar?


I'm using Python3 and PyQt5, make my widgets and windows in Qt Designer. What is more, I do not generate .py files from a .ui. I simply load it using next code:

class MainWindow(QMainWindow):

def __init__(self):
    super(MainWindow, self).__init__()
    uic.loadUi('UI/Qt/source/MainWindow.ui', self)

So, I wanted to know, how do I bind menu bar actions to functions.

Is there any way I can do something like this?

self.getActionByName("actionTest_Action").connect(self.do_something)

Solution

  • It is not necessary to use findChild when using loadUi since this method adds the object to the attributes of the class using the objectName as a name, for example in this particular case a cleaner code than the other answer is:

    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            uic.loadUi('UI/Qt/source/MainWindow.ui', self)
    
            self.actionTest_Action.triggered.connect(self.test)
    
        def test(self):
            print("Test")