1、 自定义信号与槽
import sys
from PyQt5.QtWidgets import *
class ssdemo(QWidget):
def __init__(self):
super(ssdemo, self).__init__()
self.initUI()
#槽函数
def on_colik(self):
print(self.btn.text())
def initUI(self):
#添加到窗体
self.btn = QPushButton("我的按钮",self)
#链接到槽
self.btn.clicked.connect(self.on_colik)
self.resize(400,300)
self.setWindowTitle("信号与槽")
if __name__ =='__main__':
app =QApplication(sys.argv)
win =ssdemo()
win.show()
sys.exit(app.exec_())
2、两个对象的信息传递
from PyQt5.QtCore import *
class Mysingal(QObject):
# 定义一个信号
sendmsg = pyqtSignal(object)
#定义事件
def run(self):
self.sendmsg.emit("hello")
# 定义一个槽类
class Mysolt(QObject):
def get(self,msg):
print("信息:"+msg)
if __name__ =='__main__':
send = Mysingal()
solt = Mysolt()
send.sendmsg.connect(solt.get)
send.run()
send.sendmsg.disconnect(solt.get)
send.run()
定义多个参数
from PyQt5.QtCore import *
class Mysingal(QObject):
# 定义一个信号
sendmsg = pyqtSignal(object)
sendmsg1 = pyqtSignal(str,int,int)
#发送的信息
def run(self):
self.sendmsg.emit("hello")
def run1(self):
self.sendmsg1.emit("结构",10,20)
#定义一个槽
class Mysolt(QObject):
#接受的信息
def get(self,msg):
print("信息:"+msg)
def get1(self,msg,a,b):
print("信息是:"+msg,a+b)
if __name__ =='__main__':
send = Mysingal()
solt = Mysolt()
#绑定槽
send.sendmsg.connect(solt.get)
send.run()
send.sendmsg1.connect(solt.get1)
send.run1()
5、N对N 信号与槽链接
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
class CustSignal(QObject):
# 声明信号
sg = pyqtSignal()
s1 = pyqtSignal(int)
s2 = pyqtSignal(int, str)
s3 = pyqtSignal(list)
# 声明承载信号,槽函数的参数可以是 int,或str类型,也可以只有一个str
# singal6 =pyqtSignal([int,str],[str]) #[]重载 或的关系 可以是两个参数也可以是1个参数
def __init__(self):
super(CustSignal, self).__init__()
self.sg.connect(self.sgcall)
self.s1.connect(self.sgcall1)
self.s3.connect(self.s3call)
self.sg.emit()
self.s1.emit(222)
self.s3.emit([1,2,3,4,5,2])
print("123123")
# 声明槽
def sgcall(self):
print("11111")
def sgcall1(self, val):
print("singal1 emit,value", val)
def s3call(self,lt):
print("s3call emit value",lt)
if __name__ == '__main__':
msok = CustSignal()
--------------------------------------------------------------------------
from PyQt5.QtCore import *
class nnsingal(QObject):
s1 = pyqtSignal()
s2 = pyqtSignal(int)
s3 = pyqtSignal(str)
def __init__(self):
super(nnsingal, self).__init__()
self.s1.connect(self.call1)
self.s2.connect(self.call2)
self.s3.connect(self.call1)
self.s1.emit()
self.s2.emit(9999)
self.s3.emit("2123123")
self.s1.disconnect(self.call1)
self.s2.disconnect(self.call2)
def call1(self):
print("s1 emit")
def call2(self,val):
print("s2 emit value", val)
def call3(self,text):
print("s3 emit value:", text)
if __name__ =='__main__':
ns = nnsingal()