PySide信号“重复”行为

时间:2011-09-28 01:08:02

标签: python qt pyqt pyside qt-signals

from PySide.QtCore import *

class Eggs(QObject):
    evt_spam = Signal()
    print "Loaded"

a = Eggs()
b = Eggs()
print a.evt_spam
print b.evt_spam
print a.evt_spam is b.evt_spam

输出:

Loaded
<PySide.QtCore.Signal object at 0xa2ff1a0>
<PySide.QtCore.Signal object at 0xa2ff1b0>
False

“已加载”仅打印一次(如预期;它是一个类变量),但为什么要创建2个信号实例(如果它也是类变量)?

1 个答案:

答案 0 :(得分:3)

创建类实例时不会打印,而是在执行类作用域时打印。此代码将打印“已加载”,即使我从未创建过“测试”的实例。

class Test:
    print "Loaded"

如果要在初始化类时运行代码,请查看__init__()。在创建实例时,此代码将打印“已加载”,而不是在定义类本身时。

class Test:
    def __init__(self):
        print "Loaded"

QT的QObject元类似乎正在重写类属性,以防止在初始化类的新实例时出现重复信号。也许您可以像这样分配属性:

class Test(QObject):
    def __init__(self, signal):
        self.evt_spam = signal

sig = Signal()
a = Test(sig)
b = Test(sig)

或者这个:

class Test(QObject):
    def signal(self, signal):
        self.evt_spam = evt_spam
        return self

evt_spam = Signal()
a = Test().signal(evt_spam)
b = Test().signal(evt_spam)