So having followed my best understanding of how to correctly use threads in Qt, I've written a small toy example in which a QObject
is moved to a running thread and a signal is called on that object when the window is clicked.
The problem I'm having is the slot is never called in the correct thread - it is always called in the main thread.
This is implemented with the following code:
from PyQt5 import QtWidgets, QtCore
class WidgetWithInput(QtWidgets.QWidget):
widgetClicked = QtCore.pyqtSignal()
def mousePressEvent(self, event):
self.widgetClicked.emit()
class MyObject(QtCore.QObject):
aSignal = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(MyObject, self).__init__(*args, **kwargs)
self.aSignal.connect(self.onASignal)
def onASignal(self):
print('MyObject signal thread: %s'
% str(int(QtCore.QThread.currentThreadId())))
class SimpleDisplay(QtWidgets.QMainWindow):
''' Class presenting the display subsytem
'''
def __init__(self, my_object, *args, **kwargs):
super(SimpleDisplay, self).__init__(*args, **kwargs)
self._my_object = my_object
self._widget = WidgetWithInput()
self.setCentralWidget(self._widget)
self._widget.widgetClicked.connect(self._do_something)
def _do_something(self):
self._my_object.aSignal.emit()
def main(run_until_time=None):
import sys
app = QtWidgets.QApplication(sys.argv)
print ('main thread: %s' % str(int(QtCore.QThread.currentThreadId())))
concurrent_object = MyObject()
display = SimpleDisplay(concurrent_object)
myobject_thread = QtCore.QThread()
myobject_thread.start()
concurrent_object.moveToThread(myobject_thread)
display.show()
exit_status = app.exec_()
myobject_thread.quit()
myobject_thread.wait()
sys.exit(exit_status)
if __name__ == '__main__':
main()
Which outputs something like:
main thread: 139939383113472
MyObject signal thread: 139939383113472
I would expect those two printed thread ids to be different.
Am I missing something here? Explicitly setting the signal to be queued doesn't change anything.