PYQT5 Tutorials-Events and Signals (5)

Source: Internet
Author: User
Tags emit

Events and signals in the PYQT5

In this part of the PYQT5 programming tutorial, we explore the occurrence of events and signals in an application.

Event

All GUI applications are event-driven. Events are primarily generated by the user actions of the app. However, events can be triggered by other conditions, such as a network connection, a window manager, and a timer, which can trigger the creation of events. When we call the application's Exec_ () method, the application enters the main loop. The main loop is used to detect the occurrence of events and to send events to the objects used for processing.

In the event model, there are three participants

    • Event Source
    • Event Object
    • Event target

The event source is the object in which the state has changed. It produces an event. The event object (evnet) encapsulates the state change in the event source. The event target is the object that you want to be notified. The event source object represents a task that handles an event until the event target responds.

The PYQT5 has a unique signal and slot mechanism to handle events. Signals and slots are used for communication between objects. When the specified event occurs, an event signal is emitted. Slots can be called by any Python script. When the signal connected to the slot is fired, the slot is called.

Signals & Slots

This example demonstrates the use of signals and slots in the PYQT5.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial in this example, we connect a signalof a qslider to a slot of a qlcdnumber. Author:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtcore import Qtfrom Pyqt5.qtwidge        TS Import (Qwidget, Qlcdnumber, Qslider, Qvboxlayout, Qapplication) class Example (Qwidget): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): LCD = Qlcdnumbe R (self) SLD = Qslider (Qt.horizontal, self) vbox = Qvboxlayout () vbox.addwidget (LCD) vbox.addwi Dget (SLD) self.setlayout (vbox) sld.valueChanged.connect (lcd.display) self.setgeometry (300, 30 0, Self.setwindowtitle (' Signal & Slots ') Self.show () if __name__ = = ' __main__ ': a pp = qapplication (sys.argv) ex = Example () sys.exit (App.exec_ ()) 

  

In our example, we show a qtgui.qlcdnumber and a Qtgui.qslider class. We can change the LCD number by dragging the handle of the slider bar.

Sld.valueChanged.connect (Lcd.display)

  

Here, we connect the valuechanged signal of the slider bar with the display slots displayed by the LCD number.

The sender is an object that sends a signal. The recipient is an object that receives a signal. A groove is a method of reacting to a signal.

Figure:signal & Slots

overriding event handler functions

Event handling in PYQT is typically handled by overriding the event handler function.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial In this example, we reimplement an event handler. Author:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtcore import Qtfrom Pyqt5.qtwidge TS Import Qwidget, Qapplicationclass Example (qwidget):        def __init__ (self):        super (). __init__ (                ) Self.initui ()                    def initui (self):                      self.setgeometry (+,-)        self.setwindowtitle (' Event handler ')        self.show ()                    def keypressevent (self, e):                if e.key () = = Qt.key_escape:            self.close ()                if __name_ _ = = ' __main__ ':        app = Qapplication (SYS.ARGV)    ex = Example ()    sys.exit (App.exec_ ())

In our example, we have rewritten the Keypressevent () event handler function.

def keypressevent (self, e):        if e.key () = = Qt.key_escape:        self.close ()

If we click the ESC button, the app will be terminated.

Event Sender

Sometimes it is convenient to know which component is the signal sender. Therefore, PYQT5 has the sender () method to solve this problem.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial In this example, we determine the event senderobject.au Thor:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtwidgets import Qmainwindow, QPUSHB Utton, Qapplicationclass Example (Qmainwindow): def __init__ (self): Super (). __init__ () self.in        Itui () def initui (self): BTN1 = Qpushbutton ("button 1", self) btn1.move (30, 50)                    BTN2 = Qpushbutton ("button 2", self) Btn2.move (btn1.clicked.connect) (self.buttonclicked) Btn2.clicked.connect (self.buttonclicked) Self.statusbar () self.setgeometry (290, Self.setwindowtitle) (' Event sender ') self.show () def buttonclicked (SE                LF): Sender = Self.sender () Self.statusbar (). ShowMessage (Sender.text () + ' was pressed ') if __name__ = = ' __main__ ': app = Qapplication (sys.argv) ex = Example () sys.exit (App.exec_ ()) 

In our example, we have two buttons. In the buttonclikced () method, we call the sender () method to determine which button we pressed.

Btn1.clicked.connect (self.buttonclicked)            btn2.clicked.connect (self.buttonclicked)

Two buttons are connected to the same slot.

def buttonclicked (self):      sender = Self.sender ()    Self.statusbar (). ShowMessage (Sender.text () + ' is pressed ')

We call the sender () method to determine which signal source is sending the signal. It then displays the label contents of the pressed button on the app's status bar.

Figure:event Sender

Send Signal

An object generated from QOBEJCT can send a signal. In the example below we will see how to send a custom signal.

#!/usr/bin/python3#-*-coding:utf-8-*-"" "Zetcode PyQt5 Tutorial in this example, we show how to emit asignal. Author:jan Bodnarwebsite:zetcode.com last Edited:january "" "Import sysfrom pyqt5.qtcore import pyqtsignal, QOBJECTF Rom pyqt5.qtwidgets import Qmainwindow, Qapplicationclass communicate (qobject): Closeapp = pyqtsignal () class E                    Xample (Qmainwindow): def __init__ (self): Super (). __init__ () Self.initui () def initui (self): SELF.C = Communicate () Self.c.closeapp.connect (self.close) sel F.setgeometry (290) self.setwindowtitle (' Emit signal ') self.show () def MOUS Epressevent (self, event): Self.c.closeapp.emit () if __name__ = = ' __main__ ': app = QAp Plication (SYS.ARGV) ex = Example () sys.exit (App.exec_ ()) 

We create a new signal called Closeapp. The signal is emitted when a mouse click event is triggered. The signal is connected to the close () method of the Qmainwindow.

Class Communicate (Qobject):        Closeapp = pyqtsignal ()     

The signal is created using the Pyqtsignal () method and becomes an attribute of the outer class communicate class.

Connect the custom Closeapp signal to the close () slot on the Qmainwindow.

def mousepressevent (self, event):        Self.c.closeapp.emit ()

When we click the mouse on the window, the Closeapp signal will be fired. Application interruption.

In this part of the PYQT5 tutorial, we have an overview of the signal-trough mechanism.

PYQT5 Tutorials-Events and Signals (5)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.