为什么我需要用 pyqtSlot 装饰连接的插槽? [英] Why do I need to decorate connected slots with pyqtSlot?

查看:51
本文介绍了为什么我需要用 pyqtSlot 装饰连接的插槽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pyqt5,并且使用类似于以下的代码连接了多个方法:

I'm using pyqt5, and I have several methods connected using code similar to the following:

self.progress.canceled.connect(self.cancel)

例如,self.cancel 是:

def cancel(self):
    self.timer.stop()

这段代码似乎在多种情况下都能正常工作,没有用 pyqtSlot 装饰 cancel 或用它做任何特别的事情.

This code seems to work cleanly in multiple scenarios, without ever decorating cancel with pyqtSlot or doing anything special with it.

我的问题是:

  1. 这样做我失去了什么?
  2. 需要 pyqtSlot 的原因是什么?
  1. What am I losing by doing it this way?
  2. What is the reason pyqtSlot is required?

推荐答案

pyqtSlot 允许定义多个不同的插槽重载,每个重载都有不同的签名.有时在进行跨线程连接时也可能需要它(请参阅此答案以了解此类情况).然而,这些用例相对较少,并且在大多数 PyQt 应用程序中根本没有必要使用 pyqtSlot.信号可以连接到任何 python 可调用对象,无论它是否装饰为槽.

The main purpose of pyqtSlot is to allow several different overloads of a slot to be defined, each with a different signature. It may also be needed sometimes when making cross-thread connections (see this answer for one such scenario). However, these use-cases are relatively rare, and in most PyQt applications it is not necessary to use pyqtSlot at all. Signals can be connected to any python callable object, whether it is decorated as a slot or not.

PyQt 文档还指出:

The PyQt docs also state:

将信号连接到修饰的 Python 方法还具有减少内存使用量的优势,并且速度稍快.

Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster.

但是,在实践中,这种优势通常很小,经常会被其他因素所淹没.它对原始信号速度几乎没有影响,并且在它开始对 CPU 负载或内存使用产生重大影响之前,有必要进行 数千 次发射/连接.有关这些要点的深入分析,请参阅@Schollii 撰写的这篇代码项目文章:

However, in practice, this advantage is generally very small and will often be swamped by other factors. It has very little affect on raw signalling speed, and it would be necessary to make thousands of emits/connections before it started to have a significant impact on cpu load or memory usage. For an in depth analysis of these points, see this Code Project article by @Schollii:

这篇关于为什么我需要用 pyqtSlot 装饰连接的插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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