在pyqt4中自定义new-style Signal

apt中搜索pyqt4,在pyqt5出来后,就被改名为python-qt4,一股淡淡的忧伤~

今天试着写一个自定义的新式信号(new-style Signal),却总是报错,错误的代码如下:


#!/usr/bin/python
#coding:utf-8
'''这是错误代码~~~~'''
import sys
from PyQt4.QtCore import QObject, pyqtSignal, QCoreApplication
from PyQt4.QtGui import QWidget
class A(QObject):
    def __init__(self,parent=None):
        QObject.__init__(self)
        self.mySignal = pyqtSignal()
    def useSignal(self):
        self.mySignal.emit()

class B(QObject):
    def __init__(self,parent=None):
        QObject.__init__(self)
        self.a = A()
        self.a.mySignal.connect(self.printASent)
        self.a.useSignal()
        
    def printASent(self):
        print 'Signal is called.'
        
if __name__ == '__main__':
    app = QCoreApplication(sys.argv)
    b = B()
    sys.exit(app.exec_())
出错代码:self.a.mySignal.connect(self.printASent)
AttributeError: 'PyQt4.QtCore.pyqtSignal' object has no attribute 'connect'


为什么会这样呢,在google了一下后得到解决方案,将mySignal作为类属性来定义,即为如下代码:


#!/usr/bin/python
#coding:utf-8
import sys
from PyQt4.QtCore import QObject, pyqtSignal, QCoreApplication
from PyQt4.QtGui import QWidget
class A(QObject):
    def __init__(self,parent=None):
        QObject.__init__(self)

    '''作为类属性来定义'''
    mySignal = pyqtSignal()
    
    def useSignal(self):
        self.mySignal.emit()

class B(QObject):
    def __init__(self,parent=None):
        QObject.__init__(self)
        self.a = A()
        self.a.mySignal.connect(self.printASent)
        self.a.useSignal()  def printASent(self):
        print 'Signal is called.'
        
if __name__ == '__main__':
    app = QCoreApplication(sys.argv)
    b = B()
    sys.exit(app.exec_())
此时运行就能得到正确结果。


为了一探究竟,又去翻了一下PyQt4的官方文档。

http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html#unbound-and-bound-signals

“A signal (specifically an unbound signal) is an attribute of a class that is a sub-class of QObject. When a signal is referenced as an attribute of an instance of the class then PyQt4 automatically binds the instance to the signal in order to create a bound signal. This is the same mechanism that Python itself uses to create bound methods from class functions.”

上面一句话提出了这3个要点:

1.signal(明确的说是一个非绑定的signal)是QObject子类的一个属性.

2.singal被作为一个类实例对象的引用时,PyQt4自动的绑定这个实例对象至signal来创建一个绑定的signal(bound signal).

3.这和,Python从类函数中创建绑定方法,是同样的机制


一句话,把mySignal定义为类属性,然后在使用时把他绑定为对象属性吧。


你可能感兴趣的:(Signal,pyqt4)