如何动态创建pyqtSignals [英] How to create pyqtSignals dynamically

查看:64
本文介绍了如何动态创建pyqtSignals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在需要时在运行时创建信号?

Is there any possibility to create signals at runtime when needed?

我正在一个函数中做这样的事情:

I'm doing something like this in a function:

class WSBaseConnector(QObject)

    def __init__(self) -> None:
        super(QObject, self).__init__()    
        self._orderBookListeners: Dict[str, pyqtSignal[OrderBookData]] = {}

    def registerOrderBookListener(self, market: str, listener: Callable[[OrderBookData], None], loop: AbstractEventLoop) -> None:
            try:
                signal = self._orderBookListeners[market]
            except KeyError:
                signal = pyqtSignal(OrderBookData)
                signal.connect(listener)
                self._orderBookListeners[market] = signal
            else:
                signal.connect(listener)

如您所见,我有一个存储 str、pyqtSignal 对的字典.当我尝试将信号连接到侦听器时,出现错误:

As you can see, I have a dict that stores str, pyqtSignal pairs. When I try to connect the signal to the listener I get the error:

'PyQt5.QtCore.pyqtSignal' object has no attribute 'connect'

在没有类变量的情况下,是否无法在运行时创建 pyqtSignals?

Is it not possible to create pyqtSignals at runtime without been class vars?

干杯.

推荐答案

不,这是不可能的.pyqtSignal 对象 是一个工厂函数,它返回一个 descriptor,所以必须在class语句执行时创建.引用文档:

No, it is not possible. The pyqtSignal object is a factory function that returns a descriptor, so it must be created when the class statement is executed. To quote from the docs:

新信号只能在 QObject 的子类中定义.他们必须是类定义的一部分,不能动态添加定义类后作为类属性.

New signals should only be defined in sub-classes of QObject. They must be part of the class definition and cannot be dynamically added as class attributes after the class has been defined.

以这种方式定义的新信号将自动添加到类的 QMetaObject.这意味着它们将出现在 Qt Designer 中并且可以使用 QMetaObject API 进行内省.[强调]

New signals defined in this way will be automatically added to the class’s QMetaObject. This means that they will appear in Qt Designer and can be introspected using the QMetaObject API. [emphasis added]

您的代码正在创建未绑定信号对象,这就是您收到属性错误的原因.绑定和未绑定信号之间的区别与类的方法完全相同.从文档中再次引用:

Your code is creating unbound signal objects, which is why you get the attribute error. The distinction between bound and unbound signals is exactly the same as with the methods of classes. To quote again from the docs:

信号(特别是未绑定的信号)是一个类属性.当一个信号被引用为类的实例的属性然后PyQt5 自动将实例绑定到信号以便创建绑定信号.这与 Python 本身的机制相同用于从类函数创建绑定方法.

A signal (specifically an unbound signal) is a class attribute. When a signal is referenced as an attribute of an instance of the class then PyQt5 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.

这篇关于如何动态创建pyqtSignals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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