如何利用 Python 的 PyQt 库来管理线程
PyQt 为在 Python 应用程序中构建图形用户界面提供了一个强大的框架。为了确保执行后台任务时 UI 更新流畅且响应灵敏,Qt 利用与主 GUI 线程同时运行的线程。然而,有效地使用线程需要仔细考虑。
正如 Maya Posch 的文章中所述,重新实现 run 方法不应成为使用 QThreads 时的首选方法。相反,请考虑使用信号和槽来促进线程之间的通信。为了说明正确的实现,将提供一个实际示例。
PyQt 线程管理示例
在示例中,我们创建一个单独的工作线程来处理长计算而主 GUI 线程则管理图形界面。工作线程通过信号将状态更新传达给 GUI。
要开始计算,用户单击“开始”按钮。 “取消”按钮可用于终止操作并重置工作线程。请注意,通常不建议强制终止线程,但用于演示目的。
Python 代码
<code class="python">from PyQt4 import QtGui, QtCore import sys import random class Example(QtCore.QObject): signalStatus = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(self.__class__, self).__init__(parent) # Create a gui object. self.gui = Window() # Create a new worker thread. self.createWorkerThread() # Make any cross object connections. self._connectSignals() self.gui.show() def _connectSignals(self): self.gui.button_cancel.clicked.connect(self.forceWorkerReset) self.signalStatus.connect(self.gui.updateStatus) self.parent().aboutToQuit.connect(self.forceWorkerQuit) def createWorkerThread(self): # Setup the worker object and the worker_thread. self.worker = WorkerObject() self.worker_thread = QtCore.QThread() self.worker.moveToThread(self.worker_thread) self.worker_thread.start() # Connect any worker signals self.worker.signalStatus.connect(self.gui.updateStatus) self.gui.button_start.clicked.connect(self.worker.startWork) def forceWorkerReset(self): if self.worker_thread.isRunning(): print('Terminating thread.') self.worker_thread.terminate() print('Waiting for thread termination.') self.worker_thread.wait() self.signalStatus.emit('Idle.') print('building new working object.') self.createWorkerThread() def forceWorkerQuit(self): if self.worker_thread.isRunning(): self.worker_thread.terminate() self.worker_thread.wait() class WorkerObject(QtCore.QObject): signalStatus = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(self.__class__, self).__init__(parent) @QtCore.pyqtSlot() def startWork(self): for ii in range(7): number = random.randint(0,5000**ii) self.signalStatus.emit('Iteration: {}, Factoring: {}'.format(ii, number)) factors = self.primeFactors(number) print('Number: ', number, 'Factors: ', factors) self.signalStatus.emit('Idle.') def primeFactors(self, n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button_start = QtGui.QPushButton('Start', self) self.button_cancel = QtGui.QPushButton('Cancel', self) self.label_status = QtGui.QLabel('', self) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button_start) layout.addWidget(self.button_cancel) layout.addWidget(self.label_status) self.setFixedSize(400, 200) @QtCore.pyqtSlot(str) def updateStatus(self, status): self.label_status.setText(status) if __name__=='__main__': app = QtGui.QApplication(sys.argv) example = Example(app) sys.exit(app.exec_())</code>
此示例演示了 QThreads 在PyQt 应用程序,允许高效的后台操作,而不会冻结用户界面。
以上是如何有效管理 PyQt 应用程序中的线程?的详细内容。更多信息请关注PHP中文网其他相关文章!