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())

class Worker(QtCore.QThread):

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

    def run(self):
        self.running = True
        i = 0
        while self.running:
            i += 1

    def stop(self):
        self.running = False

    def update_value(self,value):

NB: I use the new style signal and slots

Leave a Comment