博客
关于我
PyQt5“定时器不能从另一个线程启动“更改 QLabel 的大小时出错
阅读量:801 次
发布时间: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/

你可能感兴趣的文章
pyspider爬虫学习-文档翻译-Architecture.md
查看>>
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it‘s not in your path
查看>>
Pytesseract集字符白名单
查看>>
Pytest ------ 标记函数
查看>>
Pytest Fixture的妙用:深度解析范围和实际运用!
查看>>
Pytest monkeypatch不适用于导入的函数
查看>>
Pytest 命令行报错: Hint: make sure your test modules/packages have valid Python names.
查看>>
pytest 的 request fixture:实现个性化测试需求
查看>>
Pytest+Allure 接口自动化测试平台开发实战
查看>>
pytest+allure使用动态级别,参数化severity
查看>>
Pytest+Unittest+Git+Jenkins企业级CICD自动化测试平台建设方案
查看>>
Pytest+Yaml 数据驱动测试用例
查看>>
pytest-base-url插件之配置可选的项目系统URL
查看>>
pytest-xdist 进行多进程并发测试!
查看>>
pytest-xdist:远程多主机 - 分布式运行自动化测试
查看>>
Pytest中doctests的测试方法应用!
查看>>
Pytest中进行测试环境切换:pytest_addoption!
查看>>
pytest利用request fixture实现个性化测试需求详解
查看>>
pytest单元测试实战
查看>>
pytest单元测试框架
查看>>