pyqt5 计时器事件在 qthread 中不起作用?

the pyqt5 timer event not working in a qthread?

我需要在线程中计算一个数字然后处理数据,但是线程中的计时器不工作。

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt, QObject, QThread, pyqtSlot, QTimer
import sys, time

class Worker(QObject):
    def __init__(self):
        super().__init__()

        self.i = 0
        self.startTimer(100)

    def timerEvent(self, QTimerEvent):
        self.i += 2

    @pyqtSlot()
    def run(self):
        while True:
            print(self.i)
            time.sleep(1)

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        self.worker = Worker()
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.thread.start()

app = QApplication(sys.argv)
demo = Demo()
demo.show()
app.exec()

终端一直显示0,谁能帮帮我

信号和事件需要事件循环才能工作。当您使用 QThread 时,您会创建该事件循环,但当您使用 time.sleep() 时,您将阻止它阻止调用 timerEvent() 方法。所以解决方案是用另一个不会阻塞它的选项(QEventLoop + QTimer)替换time.sleep()

from PyQt5 import QtCore, QtWidgets


class Worker(QtCore.QObject):
    def __init__(self):
        super().__init__()

        self.i = 0
        self.m_id = self.startTimer(100)

    def timerEvent(self, event):
        if self.m_id == event.timerId():
            self.i += 2
        super().timerEvent(event)

    @QtCore.pyqtSlot()
    def run(self):
        while True:
            print(self.i)
            loop = QtCore.QEventLoop()
            QtCore.QTimer.singleShot(1000, loop.quit)
            loop.exec()


class Demo(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        thread = QtCore.QThread(self)
        self.worker = Worker()
        self.worker.moveToThread(thread)
        thread.started.connect(self.worker.run)
        thread.start()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec())