User defined signal

In addition to the specified signals, you can also create and use new signals.

In this example, we’ll use pyqtSignal() to create a custom signal and make it become released when a particular event occurs.


Example

import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMainWindow


class Communicate(QObject):

    closeApp = pyqtSignal()


class MyApp(QMainWindow):

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

        self.initUI()

    def initUI(self):

        self.c = Communicate()
        self.c.closeApp.connect(self.close)

        self.setWindowTitle('Emitting Signal')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def mousePressEvent(self, e):

        self.c.closeApp.emit()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

We made a signal called closeApp.

This signal occurs when you click the mouse and is connected to the close() slot in the QMainWindow to quit the program.


Description

class Communicate(QObject):

    closeApp = pyqtSignal()

We created a signal called closeApp as a property of the Communicate class with pyqtSignal().


self.c = Communicate()
self.c.closeApp.connect(self.close)

The closeApp signal in the Communicate class connects to the close() slot in the MyApp class.


def mousePressEvent(self, e):

    self.c.closeApp.emit()

Using the mousePressEvent event handler, we made the closeApp signal get released when the mouse was clicked.

Prev/Next