from PyQt5.QtCore import QObject, pyqtSignal
class QTypeSignal(QObject):
sendmsg = pyqtSignal(object) # 使用pyqtSignal类实列发射信号, object 信号发射参数的类型, 用于处理一个参数的时候
def __init__(self):
super().__init__()
def run(self):
self.sendmsg.emit('hello world') # 信号具体传递的数据信息
class QTypeSlot(QObject):
def __init__(self):
super().__init__()
def get(self, msg): # 处理函数的参数接收,注意个数对应
print('QSlot get msg => ' + msg)
send = QTypeSignal()
slot = QTypeSlot()
send.sendmsg.connect(slot.get) # 连接信号与槽
send.run()
传入多个信号参数
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
class WinForm(QWidget):
button_clicked_signal = pyqtSignal(str, int) # 信号需要传入指定类型的两个参数
def __init__(self):
super().__init__()
self.resize(500, 400)
self.btn_colse = QPushButton('close', self)
self.btn_colse.clicked.connect(self.btn_clicked)
self.button_clicked_signal.connect(self.show_edit)
self.line_edit = QLineEdit(self)
self.line_edit.move(200, 200)
def btn_clicked(self):
self.button_clicked_signal.emit('btn clicked', 1)
def show_edit(self, msg, tag):
self.line_edit.setText('msg %s, tag: %s' % (msg, tag))
app = QApplication([])
main = WinForm()
main.show()
app.exec()
信号参数重载
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal
class WinForm(QWidget):
button_clicked_signal = pyqtSignal([str, int], [int, int]) # 重载版本
def __init__(self):
super().__init__()
self.resize(500, 400)
self.btn_colse = QPushButton('close', self)
self.btn_colse.clicked.connect(self.btn_clicked)
self.button_clicked_signal[int, int].connect(self.show_edit) # 需要指定传入的参数类型
self.line_edit = QLineEdit(self)
self.line_edit.move(200, 200)
def btn_clicked(self):
self.button_clicked_signal[int, int].emit(2, 1) # 需要指定传入的参数类型
def show_edit(self, msg, tag):
self.line_edit.setText('msg %s, tag: %s' % (msg, tag))
app = QApplication([])
main = WinForm()
main.show()
app.exec()
使用自定义参数
对 clicked 触发的槽函数添加额外的参数信息
from PyQt5.QtWidgets import *
class WinForm(QWidget):
def __init__(self):
super().__init__()
self.resize(500, 400)
self.btn_colse = QPushButton('close', self)
self.btn_colse.clicked.connect(lambda: self.btn_clicked('close btn')) # 使用lambda ,自定义传入指定的参数
self.line_edit = QLineEdit(self)
self.line_edit.move(200, 200)
def btn_clicked(self, name):
self.line_edit.setText('%s is clicked' % name)
app = QApplication([])
main = WinForm()
main.show()
app.exec()