I'm trying to use QThread
ing in my PyQt application. I have a worker that constantly does something in a loop and occasionally needs to update parameters used in its loop body. I decided to solve the problem using signals. However the parameter update never happens. To demonstrate the problem, consider the following code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class A(QObject):
def run(self):
while True:
pass
def update(self):
print("Updating")
class Updater(QObject):
update_needed = pyqtSignal()
a = A()
u = Updater()
t = QThread()
a.moveToThread(t)
t.started.connect(a.run)
t.finished.connect(a.deleteLater)
u.update_needed.connect(a.update)
t.start()
u.update_needed.emit()
At first I thought the problem was that my run method wasn't allowing the QThread
enough time to process events (even though I read that QThread
would ensure this automatically - this was why I chose this threading implementation with moveToThread
instead of subclassing QThread
).
So I changed the run
method in A
to
def run(self):
return True
but update
still didn't get called.
Finally, I tried putting everything in an actual QApplication
(even though a QThread
should have its own event loop AFAIK):
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.a = A()
self.u = Updater()
t = QThread(self)
self.a.moveToThread(t)
t.started.connect(self.a.run)
t.finished.connect(self.a.deleteLater)
self.u.update_needed.connect(self.a.update)
t.start()
self.u.update_needed.emit()
class A(QObject):
def run(self):
while True:
pass
def update(self):
print("Updating")
class Updater(QObject):
update_needed = pyqtSignal()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
but this does not run update
either. Why is the update_needed
signal not registering?