Home > Article > Backend Development > How can I safely communicate data between the main window and a thread in PyQt?
Communicating Data Between Main Window and a Thread in PyQt
In PyQt applications, a common scenario involves sharing data between the main window and a thread while maintaining thread safety. Here are the recommended approaches:
Signals and Slots:
Example:
<code class="python">class Worker(QtCore.QThread): beep = QtCore.pyqtSignal(int) def __init__(self, sleep_time): super(Worker, self).__init__() self.sleep_time = sleep_time def run(self): i = 0 while True: i += 1 self.beep.emit(i) time.sleep(self.sleep_time) class MainWindow(QtGui.QWidget): def __init__(self): # ... self.worker = Worker(1) # Initial sleep time self.worker.beep.connect(self.update) self.worker.start() def update(self, number): # Update widget with number self.output.display(number)</code>
Caveats:
Other Approaches:
The above is the detailed content of How can I safely communicate data between the main window and a thread in PyQt?. For more information, please follow other related articles on the PHP Chinese website!