I’m having trouble with sending a signal from a thread within an app that I’m writing.
To keep things simple, let’s assume that the app consists of a main window which contains just a push button and a status bar, and has four classes - the MainWindow class, a Signals class, a Model class - which holds the logic functions, and a Worker class which is used to run separate threads.
When the push button is pressed, it connects to the ‘call_do_this’ function which starts a thread that calls the ‘do_this’ function in the separate Model class. The ‘do_this function’ emits a signal containing a message to be displayed in the main window status bar, and then continues with a long running process (around 14 seconds).
The simplistic code is displayed below:
class Worker(QRunnable): def __init__(self, fn=None, *args, **kwargs): super().__init__() self.fn = fn self.args = args self.kwargs = kwargs def run(self): if self.fn is not None: self.fn(*self.args, **self.kwargs) class Signals(QObject): status = pyqtSignal(str) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.threadpool = QThreadPool() self.model = Model() self.model.signals.status.connect(self.update_status_bar) self.button = QPushButton() self.button.pressed.connect(self.call_do_this) def call_do_this(self): self.worker = Worker(self.model.do_this) self.threadpool.start(self.worker) def update_status_bar(self, msg): self.statusBar().showMessage(msg) class Model(QObject): def __init__(self): super().__init__() self.signals = Signals() def do_this(self): self.signals.status.emit('This is a message') # continue with long running function
The error that occurs, is that the status bar message should be displayed as soon as the ‘do_this’ function starts, but is displayed only after the function ends. What am I doing wrong?