search
HomeBackend DevelopmentPython TutorialEvents and signals that you must learn every day in PyQt5

This article mainly introduces in detail the relevant information about events and signals that must be learned every day in PyQt5. It has a certain reference value. Interested friends can refer to it.

We will explore this part How PyQt5 events and signals are implemented in applications.

EventsEvents

All GUI applications are event-driven. Application events are primarily generated by the user, but they can also be generated by other methods, such as an Internet connection, a window manager, or a timer. When we call the application's exec_() method, the application enters the main loop. The main loop detects various events and sends them to event objects.

In the event model, there are three participants:

  • event source (event source)

  • event object (event Object)

  • event target (event target)

The event source is the state change of the object that generates events. An event object (event) is an object that encapsulates state changes in an event source. The event target is the object that wishes to be notified. The event source object represents the task of processing an event to the event target.

PyQt5 uses a unique signal and slot mechanism to handle events. Signals and slots are used for communication between objects. When a specific event occurs, a signal is emitted. The slot can be any Python call. The signal is emitted when the slot connected to it is called.

Signals & slotsSignals and slots

This is a simple example demonstrating PyQt5's signals and slots.


#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 教程

这个例子中,我们将QSlider的滑动信号连接到QLCDNumber中。

作者:我的世界你曾经来过
博客:http://blog.csdn.net/weiaitaowang
最后编辑:2016年8月1日
"""

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QSlider, 
QLCDNumber, QVBoxLayout)
from PyQt5.QtCore import Qt

class Example(QWidget):

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

 self.initUI()

 def initUI(self):

 lcd = QLCDNumber(self)
 sld = QSlider(Qt.Horizontal, self)

 vbox = QVBoxLayout()
 vbox.addWidget(lcd)
 vbox.addWidget(sld)

 self.setLayout(vbox)
 sld.valueChanged.connect(lcd.display)

 self.setGeometry(300, 300, 250, 150)
 self.setWindowTitle('信号/槽') 
 self.show()

if __name__ == '__main__':

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


In our example, QtGui.QLCDNumber and QtGui.QSlider will be used. We change the LCD numbers by dragging the slider.


sld.valueChanged.connect(lcd.display)


Here, the valueChanged signal of the slider is connected to the display slot of the lcd.

A transmitter is an object that sends signals. A receiver is an object that receives a signal. The slot is the method of feedback to the signal.

After the program is executed

Events and signals that you must learn every day in PyQt5

Override the system event handler

Events are often processed in PyQt5 through Override the event handler.


#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 教程

在这个例子中,我们执行事件处理程序。

作者:我的世界你曾经来过
博客:http://blog.csdn.net/weiaitaowang
最后编辑:2016年8月1日
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt

class Example(QWidget):

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

 self.initUI()

 def initUI(self):

 self.setGeometry(300, 300, 250, 150)
 self.setWindowTitle('事件处理') 
 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 case, we reimplement the keyPressEvent() event handler.


def keyPressEvent(self, e):
 if e.key() == Qt.Key_Escape:
 self.close()


If we press the Esc key on the keyboard, the application terminates.

Event senderEvent sending

In order to easily distinguish multiple event sources connected to the same event target, the sender() method can be used in PyQt5.


#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 教程

在这个例子中,我们确定事件发送对象。

作者:我的世界你曾经来过
博客:http://blog.csdn.net/weiaitaowang
最后编辑:2016年8月1日
"""

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton

class Example(QMainWindow):

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

 self.initUI()

 def initUI(self):

 btn1 = QPushButton('按钮一', self)
 btn1.move(30, 50)

 btn2 = QPushButton('按钮二', self)
 btn2.move(150, 50)

 btn1.clicked.connect(self.buttonClicked)
 btn2.clicked.connect(self.buttonClicked)

 self.statusBar()

 self.setGeometry(300, 300, 300, 150)
 self.setWindowTitle('事件发送') 
 self.show()

 def buttonClicked(self):

 sender = self.sender()
 self.statusBar().showMessage(sender.text() + ' 被按下')

if __name__ == '__main__':

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


In our example there are two buttons. Both buttons are connected to the buttonClicked() method and we respond to the clicked button by calling the sender() method.


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() + ' 被按下')


We determine the signal source by calling the sender() method. In the application's status bar, displays the label of the pressed button.

After the program is executed

Events and signals that you must learn every day in PyQt5

Customized emission signal

Signals can be emitted from an object created by a QObject. In the following example we will look at how we can customize the emitted signal.


#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
PyQt5 教程

在这个例子中,我们显示了如何以发射信号。

作者:我的世界你曾经来过
博客:http://blog.csdn.net/weiaitaowang
最后编辑:2016年8月1日
"""

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

class Communicate(QObject):
 closeApp = pyqtSignal()

class Example(QMainWindow):

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

 self.initUI()

 def initUI(self):

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

 self.setGeometry(300, 300, 300, 150)
 self.setWindowTitle('发射信号') 
 self.show()

 def mousePressEvent(self, event):

 self.c.closeApp.emit()

if __name__ == '__main__':

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


We create a new signal called closeApp. This signal emits a mouse press event. This signal is connected to the close() slot in QMainWindow.


class Communicate(QObject):
 closeApp = pyqtSignal()


Create a Communicate class inherited from QObject, which has a property of the pyqtSignal() class.


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


Connect our custom closeApp signal to the close() slot in QMainWindow.


def mousePressEvent(self, event):
 self.c.closeApp.emit()


When our mouse clicks on the program window, the closeApp signal is emitted (emit). Application terminated.

Related recommendations:

Python PyQt4 implements QQ drawer effect

PyQt implements interface flip switching effect


The above is the detailed content of Events and signals that you must learn every day in PyQt5. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
pyqt5怎么安装pyqt5怎么安装Nov 30, 2023 pm 02:05 PM

pyqt5安装步骤:1、确保计算机上已安装Python和pip;2、在终端或命令提示符中输入“pip install PyQt5”命令来安装PyQt5;3、安装完成后,可以在Python脚本中导入PyQt5模块并开始使用;4、可以通过输入“pip install PyQt5.QtGui”命令来安装一些特定功能或组件;5、遇到任何问题,可以尝试升级pip和setuptools。

事件 ID 4660:已删除对象 [修复]事件 ID 4660:已删除对象 [修复]Jul 03, 2023 am 08:13 AM

我们的一些读者遇到了事件ID4660。他们通常不确定该怎么做,所以我们在本指南中解释。删除对象时通常会记录事件ID4660,因此我们还将探索一些实用的方法在您的计算机上修复它。什么是事件ID4660?事件ID4660与活动目录中的对象相关,将由以下任一因素触发:对象删除–每当从ActiveDirectory中删除对象时,都会记录事件ID为4660的安全事件。手动更改–当用户或管理员手动更改对象的权限时,可能会生成事件ID4660。更改权限设置、修改访问级别或添加或删除人员或组时,可能会发生这种情

在iPhone锁屏上获取即将到来的日历事件在iPhone锁屏上获取即将到来的日历事件Dec 01, 2023 pm 02:21 PM

在运行iOS16或更高版本的iPhone上,您可以直接在锁定屏幕上显示即将到来的日历事件。继续阅读以了解它是如何完成的。由于表盘复杂功能,许多AppleWatch用户习惯于能够看一眼手腕来查看下一个即将到来的日历事件。随着iOS16和锁定屏幕小部件的出现,您可以直接在iPhone上查看相同的日历事件信息,甚至无需解锁设备。日历锁定屏幕小组件有两种风格,允许您跟踪下一个即将发生的事件的时间,或使用更大的小组件来显示事件名称及其时间。若要开始添加小组件,请使用面容ID或触控ID解锁iPhone,长按

什么是模拟信号,什么是数字信号什么是模拟信号,什么是数字信号Jan 30, 2023 pm 02:44 PM

模拟信号是指用连续变化的物理量表示的信息,其信号的幅度,或频率,或相位随时间作连续变化,或在一段连续的时间间隔内,其代表信息的特征量可以在任意瞬间呈现为任意数值的信号。数字信号是指自变量是离散的、因变量也是离散的信号,这种信号的自变量用整数表示,因变量用有限数字中的一个数字来表示;在计算机中,数字信号的大小常用有限位的二进制数表示。

超全!Python图形界面框架PyQt5使用指南!超全!Python图形界面框架PyQt5使用指南!Apr 13, 2023 am 08:43 AM

常见GUI框架 PyQt5:Qt是一个跨平台的 C++图形用户界面库。QT一度被诺基亚拥,后出售给芬兰的软件公司Digia Oyj。PyQt5是基于Digia公司Qt5的Python接口,由一组Python模块构成。PyQt5本身拥有超过620个类和6000函数及方法。在可以运行于多个平台,包括:Unix, Windows, and Mac OS。 Pyside6:Pyside是QT公司官方提供的Python包,上一版本为Pyside2,对应的是QT5,最新版命名规则进行了调整,更改为Pysid

手机无法连接WiFi的解决方法(如何解决手机有WiFi信号却无法上网的问题)手机无法连接WiFi的解决方法(如何解决手机有WiFi信号却无法上网的问题)Apr 19, 2024 pm 03:25 PM

WiFi已经成为人们日常生活中不可或缺的一部分,随着科技的发展。有时候我们的手机虽然显示有WiFi信号、然而,却无法正常连接上网。今天我们将讨论一些解决这个问题的方法,这个问题困扰着很多人。一:检查WiFi设置首先应该检查一下您的WiFi设置是否正确,如果您的手机无法连接WiFi。并且连接的是正确的WiFi网络,确保您的手机已经打开了WiFi功能。二:重新启动手机和路由器有时候,导致手机无法连接上WiFi、手机和路由器之间的通信可能会出现问题。以解决这个问题、您可以尝试重新启动手机和路由器,这时

vivo信号最强手机!vivo X100s搭载寰宇信号放大系统:21天线、360°环绕设计vivo信号最强手机!vivo X100s搭载寰宇信号放大系统:21天线、360°环绕设计Jun 03, 2024 pm 08:41 PM

5月13日消息,vivoX100s今晚正式发布,除了出色的影像,新机在信号方面表现也十分强悍。据vivo官方介绍,vivoX100s采用了创新的寰宇信号放大系统,该系统配备了高达21根天线。这一设计基于直屏进行了重新优化,以平衡5G、4G、Wi-Fi、GPS以及NFC等众多信号需求。这使得vivoX100s成为了vivo有史以来信号接收能力最强的手机。新款手机还采用了独特的360°环绕设计,天线分布在机身周围。这一设计不仅增强了信号的强度,还针对日常各种握持姿势进行了优化,避免了因握持方式不当导

在JavaScript中,"oninput"事件的用途是什么?在JavaScript中,"oninput"事件的用途是什么?Aug 26, 2023 pm 03:17 PM

当在输入框中添加值时,就会发生oninput事件。您可以尝试运行以下代码来了解如何在JavaScript中实现oninput事件-示例<!DOCTYPEhtml><html>&nbsp;&nbsp;<body>&nbsp;&nbsp;&nbsp;<p>Writebelow:</p>&nbsp;&nbsp;&nbsp;<inputtype="text"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.