PyQt5学习笔记(5) 自定义信号的使用

 1. 定义信号

ageChanged是具有两种类型参数的overload型的信号,参数可以是int也可以是str
nameChanged = pyqtSignal(str)
ageChanged = pyqtSignal([int],[str])

2. 发射信号

有多个参数时,需要带参数类型

self.ageChanged.emit(self.__age)
self.ageChanged[str].emit(ageInfo)

3.  定义槽

    @pyqtSlot(int)
    def do_ageChange_int(self,age):
        print("你的年龄"+str(age))

    @pyqtSlot(str)
    def do_ageChange_str(self,ageInfo):
        print(ageInfo)

    @pyqtSlot(str)
    def do_nameChange(self,name):
        print("你的名字"+name)

4. 信号与槽的关联

 boy.nameChanged.connect(resp.do_nameChange)

 boy.ageChanged.connect(resp.do_ageChange_int)
 boy.ageChanged[str].connect(resp.do_ageChange_str)

完整代码: 

# -*- coding: utf-8 -*-
# @Time    : 2019/11/17 20:08
# @Author  : dailinqing
# @Email   : dailinqing@126.com
# @File    : human.py
# @Software: PyCharm

import sys
from PyQt5.QtCore import QObject,pyqtSlot,pyqtSignal

class Responsor(QObject):
    @pyqtSlot(int)
    def do_ageChange_int(self,age):
        print("你的年龄"+str(age))

    @pyqtSlot(str)
    def do_ageChange_str(self,ageInfo):
        print(ageInfo)

    @pyqtSlot(str)
    def do_nameChange(self,name):
        print("你的名字"+name)

class Human(QObject):
    nameChanged = pyqtSignal(str)
    ageChanged = pyqtSignal([int],[str])


    def __init__(self,name ="mike",age=10,parent=None):
        super().__init__(parent)
        self.setAge(age)
        self.setName(name)

    def setAge(self,age):
        self.__age = age
        self.ageChanged.emit(self.__age)
        if age<18:
            ageInfo = "你是少年"
        elif 18<age<=35:
            ageInfo = "你是年轻人"
        elif 35<age<=80:
            ageInfo = "你是老人"
        else:
            ageInfo = "您是寿星"

        self.ageChanged[str].emit(ageInfo)

    def setName(self,name):
        self.__name = name
        self.nameChanged.emit(self.__name)



if __name__ =="__main__":
    boy = Human("boy",16)

    resp = Responsor()

    boy.nameChanged.connect(resp.do_nameChange)

    boy.ageChanged.connect(resp.do_ageChange_int)
    boy.ageChanged[str].connect(resp.do_ageChange_str)

    boy.setAge(35)
    boy.setName("jack")

    boy.ageChanged[str].disconnect(resp.do_ageChange_str)
    boy.setAge(10)

 

发布了62 篇原创文章 · 获赞 18 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览