PyQt5 信号、槽函数和 lambda 匿名函数
信号和槽
信号 signal
和槽 slot
是 PyQt5 的组件对象之间通信的基础。当信号触发时,连接的槽函数将会自动执行。通过 object.signal.connect()
方法连接。
内置信号
内置信号有:左键点击 clicked
、控件被激活 activated
、QAction
等的触发 triggered
、状态转换 toggle
等。
简单示例
将信号绑定或解绑到槽函数
复制self.pushButton = QtWidgets.QPushButton()
self.pushButton.clicked.connect()
self.pushButton.clicked.disconnect()
# 或者
self.action = QtWidgets.QAction()
self.action.triggered.connect()
self.action.triggered.disconnect()
自定义信号、自定义槽
- 参考: Pyqt5系列(八)-自定义信号 。
复制# -*- coding:utf-8 -*-
"""
defined Signal
"""
__author__ = 'Tony Zhu'
import sys
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QWidget, QApplication, QGroupBox, QPushButton, QLabel, QCheckBox, QSpinBox, QHBoxLayout, \
QComboBox, QGridLayout
class SignalEmit(QWidget):
helpSignal = pyqtSignal(str)
printSignal = pyqtSignal(list)
# 声明一个多重载版本的信号,包括了一个带int和str类型参数的信号,以及带str参数的信号
previewSignal = pyqtSignal([int, str], [str])
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.creatContorls("打印控制:")
self.creatResult("操作结果:")
layout = QHBoxLayout()
layout.addWidget(self.controlsGroup)
layout.addWidget(self.resultGroup)
self.setLayout(layout)
self.helpSignal.connect(self.showHelpMessage)
self.printSignal.connect(self.printPaper)
self.previewSignal[str].connect(self.previewPaper)
self.previewSignal[int, str].connect(self.previewPaperWithArgs)
self.printButton.clicked.connect(self.emitPrintSignal)
self.previewButton.clicked.connect(self.emitPreviewSignal)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('defined signal')
self.show()
def creatContorls(self, title):
self.controlsGroup = QGroupBox(title)
self.printButton = QPushButton("打印")
self.previewButton = QPushButton("预览")
numberLabel = QLabel("打印份数:")
pageLabel = QLabel("纸张类型:")
self.previewStatus = QCheckBox("全屏预览")
self.numberSpinBox = QSpinBox()
self.numberSpinBox.setRange(1, 100)
self.styleCombo = QComboBox(self)
self.styleCombo.addItem("A4")
self.styleCombo.addItem("A5")
controlsLayout = QGridLayout()
controlsLayout.addWidget(numberLabel, 0, 0)
controlsLayout.addWidget(self.numberSpinBox, 0, 1)
controlsLayout.addWidget(pageLabel, 0, 2)
controlsLayout.addWidget(self.styleCombo, 0, 3)
controlsLayout.addWidget(self.printButton, 0, 4)
controlsLayout.addWidget(self.previewStatus, 3, 0)
controlsLayout.addWidget(self.previewButton, 3, 1)
self.controlsGroup.setLayout(controlsLayout)
def creatResult(self, title):
self.resultGroup = QGroupBox(title)
self.resultLabel = QLabel("")
layout = QHBoxLayout()
layout.addWidget(self.resultLabel)
self.resultGroup.setLayout(layout)
def emitPreviewSignal(self):
if self.previewStatus.isChecked() == True:
self.previewSignal[int, str].emit(1080, " Full Screen")
elif self.previewStatus.isChecked() == False:
self.previewSignal[str].emit("Preview")
def emitPrintSignal(self):
pList = []
pList.append(self.numberSpinBox.value())
pList.append(self.styleCombo.currentText())
self.printSignal.emit(pList)
def printPaper(self, list):
self.resultLabel.setText("Print: " + "份数:" + str(list[0]) + " 纸张:" + str(list[1]))
def previewPaperWithArgs(self, style, text):
self.resultLabel.setText(str(style) + text)
def previewPaper(self, text):
self.resultLabel.setText(text)
def keyPressEvent(self, event):
if event.key() == Qt.Key_F1:
self.helpSignal.emit("help message")
def showHelpMessage(self, message):
self.resultLabel.setText(message)
# self.statusBar().showMessage(message)
if __name__ == '__main__':
app = QApplication(sys.argv)
dispatch = SignalEmit()
sys.exit(app.exec_())
内置信号、自定义槽函数和 lambda 匿名函数
当 PyQt5 中的组件触发内置信号,要触发自定义槽函数时,槽函数的参数可能不符合内置槽函数的格式,需要 lambda
匿名函数来引用。
复制class Test:
def printStr(self, string: str):
print(string)
def doal(self):
self.pushButton = QtWidgets.QPushButton()
self.pushButton.clicked.connect(lambda: self.printStr("123"))
lambda:
与 self.printStr("123")
中间包含 1 个空格。
作者:Yogile
出处:https://www.cnblogs.com/Yogile/p/16417309.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构