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

你可能感兴趣的文章
Python Flower库:分布式任务管理与监控
查看>>
Python for 循环和迭代器行为
查看>>
Python For循环多次返回
查看>>
python frame_python3 selenium自动化 frame表单嵌套的切换方法
查看>>
Python ftplib - 指定端口
查看>>
Python furl库:一键搞定复杂URL操作
查看>>
Python GC 也会关闭文件吗?
查看>>
python gen_key.py 报错 提示找不到OpenSSL lib
查看>>
python getattrribute_Python学习——面向对象高级之反射
查看>>
Python进阶语法:字典推导式
查看>>
python gil_Python中GIL的使用详解
查看>>
python glob.glob使用
查看>>
python glob的安装和使用
查看>>
Python google drive API 下载,文件在哪里?
查看>>
Python GPS 模块:读取最新的 GPS 数据
查看>>
python grpc入门
查看>>
python gRPC测试helloworld
查看>>
python gRPC简单示例
查看>>
Python GUI 开发:全面指南
查看>>
Python hashlib模块
查看>>