Make event handler

The function used in PyQt for event (signal) processing is called event handler (slot).

Let’s define a function (slot) that changes the size of the window when a signal occurs for pressing the ‘Big’ and ‘Small’ buttons.


Example

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLCDNumber, QDial, QPushButton, QVBoxLayout, QHBoxLayout)


class MyApp(QWidget):

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

        self.initUI()

    def initUI(self):

        lcd = QLCDNumber(self)
        dial = QDial(self)
        btn1 = QPushButton('Big', self)
        btn2 = QPushButton('Small', self)

        hbox = QHBoxLayout()
        hbox.addWidget(btn1)
        hbox.addWidget(btn2)

        vbox = QVBoxLayout()
        vbox.addWidget(lcd)
        vbox.addWidget(dial)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        dial.valueChanged.connect(lcd.display)
        btn1.clicked.connect(self.resizeBig)
        btn2.clicked.connect(self.resizeSmall)

        self.setWindowTitle('Signal and Slot')
        self.setGeometry(200, 200, 200, 250)
        self.show()

    def resizeBig(self):
        self.resize(400, 500)

    def resizeSmall(self):
        self.resize(200, 250)


if __name__ == '__main__':

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

The window can be enlarged and reduced by pressing the ‘Big’ and ‘Small’ buttons.


Description

btn1.clicked.connect(self.resizeBig)
btn2.clicked.connect(self.resizeSmall)

btn1 and btn2 are connected to resizeBig, resizeSmall slots, respectively.


def resizeBig(self):
    self.resize(400, 500)

def resizeSmall(self):
    self.resize(200, 250)

The resizeBig() method extends the screen size to 400px by 500px, and the resizeSmall() method reduces the screen size to 200px by 250px.


Results

../_images/6_2_event_handler_1.png ../_images/6_2_event_handler_2.png

Figure 7-2. Make event handler.


Prev/Next