Derived classes receiving signals in wrong thread in PySide (Qt/PyQt)

我的未来我决定 提交于 2019-12-06 04:18:20

Using Python 2.7.10 and PySide 1.2.2 on Windows I made a similar example and found the same issue. And yes, when connecting to the derived class the code does actually seem to be stuck in the main thread (I checked this by blocking the main thread to show that the listener no longer responds). Here's the minimal example I used:

from PySide import QtCore, QtGui
import threading, time, sys

class Signaller(QtCore.QObject):
    signal = QtCore.Signal()
    def send_signals(self):
        while True:
            self.signal.emit()
            time.sleep(1)

class BaseListener(QtCore.QObject):
    @QtCore.Slot()
    def on_signal(self):
        print 'Got signal in', threading.current_thread().name

class DerivedListener(BaseListener):
    pass

class App(QtGui.QApplication):
    def __init__(self, sys_argv):
        super(App, self).__init__(sys_argv)

        # self.listener = BaseListener()
        self.listener = DerivedListener()
        self.listener_thread = QtCore.QThread()
        self.listener.moveToThread(self.listener_thread)

        self.signaller = Signaller()
        self.signaller_thread = QtCore.QThread()
        self.signaller.moveToThread(self.signaller_thread)
        self.signaller.signal.connect(self.listener.on_signal)
        self.signaller_thread.started.connect(self.signaller.send_signals)

        self.listener_thread.start()
        self.signaller_thread.start()

sys.exit(App(sys.argv).exec_())

I found several workarounds:

  • remove the @QtCore.Slot decorator from the base class (it's generally unnecessary anyway)
  • adding an unused argument to the base class's @QtCore.Slot decorator, e.g. @QtCore.Slot(int), but only if the argument is not actually passed as an argument to the method. Perhaps adding this dummy argument essentially invalidates the decorator.
  • use PyQt4

So yes, it seems that subclassing a class that already has a slot defined with a decorator cannot be properly moved to a thread. I'm also curious to know why exactly this is.

PySide bug here: https://bugreports.qt.io/browse/PYSIDE-249

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!