PySide 信号“复制"行为 [英] PySide Signal "duplicating" behavior

查看:63
本文介绍了PySide 信号“复制"行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Loaded"只打印一次(正如预期的那样;它是一个类变量),但是为什么要创建信号的 2 个实例(如果它也是一个类变量)?

"Loaded" only printing once (as expected; it is a class variable), but why are 2 instances of the signal being created (if it is also a class variable)?

推荐答案

它不会在您创建类实例时打印,而是在执行类作用域时打印.这段代码将打印已加载",即使我从未创建过测试"的实例.

It's not being printed when you create a class instance, but rather when the class scope is executed. This code will print "Loaded", even though I never made an instance of "Test".

class Test:
    print "Loaded"

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

If you want to run code when the class is initialized, take a look at __init__(). This code will print "Loaded" when an instance is made, instead of when the class itself is defined.

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

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

QT's QObject metaclass appears to be rewriting the class attributes to prevent duplicate signals when you initialize a new instance of the class. Perhaps you can assign the attribute like this:

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)

这篇关于PySide 信号“复制"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆