0

I am very new to using PyQt and am trying to understand the signal slot mechanism. Unfortunately, documentation for PyQt often leads to Qt pages where syntax and parameters are hardly the same. I am trying to figure out 2 things in the simple example below.

1) QAction::triggered() is a void function, so how are we calling QAction::triggered.connect() on some sort of object that would theoretically be returned by the triggered() method.

2) And what is "qApp". I don't know what type qApp is or where it is created by PyQt but it seems to appear out of nowhere to me, only to be used at a convenient time.

Part of my misunderstanding probably comes from the fact that the C++ and python implementation of functions in Qt/PyQt are not the same but we are expected to understand what is going on without any sort of python docs.

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon


class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        exitAction = QAction(QIcon('exit24.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Toolbar')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
Max
  • 2,072
  • 5
  • 26
  • 42

1 Answers1

1

1/ : The syntax to connect a signal automatically carry the arguments to the dedicated callback In your case, there is no argument. I simplify your code to show you the callback mechanism

2/ : the qApp is a kind of shortcut to your Qapplication instance. You could replace it with your QApplication instance as in the following example.

Extract from the QApplication documentation :

The QApplication object is accessible through the instance() function that returns a pointer equivalent to the global qApp pointer.

The global qApp pointer refers to this application object. Only one application object should be created.

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication

class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        exitAction = QAction('Exit', self)
        exitAction.triggered.connect(self.this_call)
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)
        self.show()

    def this_call(self):
        print('bye bye')
        app.quit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
Community
  • 1
  • 1
reno-
  • 325
  • 2
  • 10