In PyQt, what is the best way to share data between the main window and a thread

Widgets are not thread safe, see Threads and QObjects:

Although QObject is reentrant, the GUI classes, notably QWidget and
all its subclasses, are not reentrant. They can only be used from the
main thread.

And see more definitions here: Reentrancy and Thread-Safety


You should only use widgets in the main thread, and use signal and slots to communicate with other threads.

I don’t think a global variable would work, but I honestly don’t know why.


How to use signals in this example:

#in main
self.worker = Worker(self.spinbox.value())
self.worker.beep.connect(self.update)
self.spinbox.valueChanged.connect(self.worker.update_value)

class Worker(QtCore.QThread):
    beep=QtCore.pyqtSignal(int)

    def __init__(self,sleep_time):
        super(Worker, self).__init__()
        self.running = False
        self.sleep_time=sleep_time

    def run(self):
        self.running = True
        i = 0
        while self.running:
            i += 1
            self.beep.emit(i)
            time.sleep(self.sleep_time)

    def stop(self):
        self.running = False

    def update_value(self,value):
        self.sleep_time=value

NB: I use the new style signal and slots

Leave a Comment