博客
关于我
PyQt5“定时器不能从另一个线程启动“更改 QLabel 的大小时出错
阅读量:799 次
发布时间:2023-03-05

本文共 3511 字,大约阅读时间需要 11 分钟。

在 PyQt5 中跨线程操作的解决方案

在 PyQt5 中,由于 GUI 组件的创建和修改通常必须在主线程(QApplication 的实例所在线程)中进行,因此你不能从其他非主线程中启动定时器或者更改标签的大小等操作。以下是一些解决这一问题的方法。

方法一:使用 pyqtSignalmoveToThread

首先,你需要定义一个信号,然后在主线程中连接这个信号到一个槽函数,然后从槽函数中启动定时器或修改标签大小。

import sysfrom PyQt5.QtWidgets import QApplication, QLabel, QPushButtonfrom PyQt5.QtCore import QObject, Qt, pyqtSignal, QThread, Timer
class Worker(QObject):    updateText = pyqtSignal(str)    def __init__(self):        super().__init__()        self.timer = Timer()        self.timer.timeout.connect(self.on_timer_timeout)        self.timer.start(1000)  # 每秒触发一次    @pyqtSlot()    def onTimerTimeout(self):        newText = "New Text"        self.updateText.emit(newText)
class MainWindow(QWidget):    def __init__(self):        super().__init__()        self.label = QLabel("Initial Text")        layout = QVBoxLayout()        layout.addWidget(self.label)        button = QPushButton("Start")        button.clicked.connect(self.start_worker)        layout.addWidget(button)        self.setLayout(layout)    def start_worker(self):        if not hasattr(self, 'worker'):            self.worker = Worker()            self.worker.updateText.connect(self.on_text_updated)
app = QApplication([])window = MainWindow()window.show()if __name__ == '__main__':    sys.exit(app.exec_())

方法二:使用 QThreadPoolmoveToThread

另一种方法是将任务放入一个线程池中执行。

import sysfrom PyQt5.QtWidgets import QApplication, QLabel, QPushButtonfrom PyQt5.QtCore import Qt, pyqtSignal, QObject, QRunnable, QThreadPool
class Worker(QObject):    updateText = pyqtSignal(str)    def __init__(self):        super().__init__()        self.timer = Timer()        self.timer.timeout.connect(self.on_timer_timeout)        self.timer.start(1000)  # 每秒触发一次    @pyqtSlot()    def onTimerTimeout(self):        newText = "New Text"        self.updateText.emit(newText)
class WorkerRunnable(QRunnable):    def __init__(self, worker):        super().__init__()        self.worker = worker    def run(self):        self.worker.start()
if __name__ == '__main__':    app = QApplication([])    window = MainWindow()    window.show()    thread_pool = QThreadPool()    worker = Worker()    runnable = WorkerRunnable(worker)    thread_pool.start(runnable)    worker.updateText.connect(lambda text: window.label.setText(text))    sys.exit(app.exec_())

方法三:使用 QMetaObject.invokeMethod

如果你不能使用信号槽机制(如上两种方法),可以尝试通过 QMetaObject.invokeMethod 来间接在主线程中执行操作。

import sysfrom PyQt5.QtWidgets import QApplication, QLabelfrom PyQt5.QtCore import Qt, pyqtSlot, QThreadPool, QRunnable, QMetaObject
class Worker(QObject):    def __init__(self, label):        super().__init__()        self.label = label        self.timer = Timer()        self.timer.timeout.connect(self.on_timer_timeout)        self.timer.start(1000)
@pyqtSlot()    def onTimerTimeout(self):        newText = "New Text"        QMetaObject.invokeMethod(self.label, "setText", Qt.DirectConnection,                                pyqtArgs(newText))
class MainWindow(QWidget):    def __init__(self):        super().__init__()        self.label = QLabel("Initial Text")        layout = QVBoxLayout()        layout.addWidget(self.label)        button = QPushButton("Start")        button.clicked.connect(self.start_worker)        layout.addWidget(button)        self.setLayout(layout)    def start_worker(self):        if not hasattr(self, 'worker'):            self.worker = Worker(self.label)
if __name__ == '__main__':    app = QApplication([])    window = MainWindow()    window.show()    sys.exit(app.exec_())

转载地址:http://hdafk.baihongyu.com/

你可能感兴趣的文章
pytest单元测试框架
查看>>
Pytest参数详解 — 基于命令行模式
查看>>
pytorch cv2 plt transforms pause waitforbuttonpress一个完整的图片处理程序
查看>>
pytest学习和使用 - Pytest用例执行结果有哪几种状态?
查看>>
pytest实战技巧之参数化应用!
查看>>
Pytest实践:Python测试技术基础知识!
查看>>
Pytest接口自动化测试实战演练
查看>>
Pytest插件pytest-selenium-让自动化测试更简洁
查看>>
Pytest数据驱动怎么玩?实战教程来了!
查看>>
Pytest数据驱动怎么玩?实战教程来了!
查看>>
pytest文档25-conftest.py作用范围
查看>>
Pytest框架 之【用例执行顺序】
查看>>
Pytest框架中的测试用例执行方式!
查看>>
pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
查看>>
Pytest框架环境切换实战教程!赶快收藏
查看>>
Pytest测试实战|Conftest.py详解
查看>>
Pytest测试框架快速搭建
查看>>
pytest测试框架:最强大的自动化测试工具,让测试变得轻松有趣
查看>>
pytest简介及jenkins集成
查看>>
Pytest自动化框架运行全局配置文件pytest.ini
查看>>