【问题标题】:How often are objects copied when passing across PyQt signal/slot connections?通过 PyQt 信号/插槽连接时,对象多久被复制一次?
【发布时间】:2015-08-21 01:58:30
【问题描述】:

This interesting article 评估对象在通过 Qt 中的信号/插槽连接传递时复制的频率。基本上,结果是当在 C++ 中通过 const 引用传递时,对象要么根本不复制(对于直接连接),要么复制一次(对于排队连接)。

PyQt 怎么样?是否同样成立?对于 Python 对象,当一个副本被复制时,它是一个深拷贝吗?

我主要对 PyQt5 和 Python 3 感兴趣。

【问题讨论】:

  • 你为什么不试试看会发生什么?

标签: python pyqt signals-slots pyqt5


【解决方案1】:

正如@ekhumoro 所建议的,我确实尝试过,但令人惊讶的是,我得到的结果与在 C++ 中进行的测试所揭示的结果不同。基本上,我的测试表明:对象根本不会被复制,即使使用 QueuedConnection 跨线程边界传递也是如此

考虑以下测试代码:

class Object2(QObject):

    def __init__(self):
        super().__init__()

    @pyqtSlot(object)
    def slot(self, data):
        print("Received data %s in thread %s" % (data, QThread.currentThread()))
        while len(data) < 10:
            time.sleep(1)
            print("Current data is %s" % data)


class Object1(QObject):

    def __init__(self):
        super().__init__()

    sig = pyqtSignal(object)

    @pyqtSlot()
    def emit_in_thread(self):
        self.data = [1]
        print("Emitting data %s in thread %s" % (self.data, QThread.currentThread()))
        self.sig.emit(self.data)
        while len(self.data) < 10:
            time.sleep(1)
            self.data += [1]
            print("Modified data to %s" % self.data)

# App
q_app = QApplication(sys.argv)

# Setup
thread = QThread()
obj1 = Object1()
obj1.moveToThread(thread)
thread.start()
obj2 = Object2()
obj1.sig.connect(obj2.slot, type=Qt.QueuedConnection)

# Emit soon
QTimer.singleShot(200, obj1.emit_in_thread)

# Run event loop
sys.exit(q_app.exec_())

结果是:

Emitting data [1] in thread <PyQt5.QtCore.QThread object at 0x7f037619f948>
Received data [1] in thread <PyQt5.QtCore.QThread object at 0x7f037619faf8>
Current data is [1]
Modified data to [1, 1]
Current data is [1, 1]
Modified data to [1, 1, 1]
Current data is [1, 1, 1]
Modified data to [1, 1, 1, 1]
Current data is [1, 1, 1, 1]
...

这表明尽管发射槽和接收槽位于不同的线程中,但它们确实共享通过 QueuedConnection 发送的data 对象。

【讨论】:

  • 现在您已经回答了自己的问题,这让我想起了 something similar 之前出现过 - 我什至自己回答了!
  • 谢谢!在另一个问题中非常有用的答案。
猜你喜欢
  • 2011-08-16
  • 2018-02-28
  • 2012-07-13
  • 1970-01-01
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
相关资源
最近更新 更多