PyQt5:线程中的计时器 [英] PyQt5: Timer in a thread

查看:121
本文介绍了PyQt5:线程中的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述

我正在尝试制作一个应用程序来收集数据、处理数据、显示数据和执行一些操作(打开/关闭阀门等).作为对我有一些更严格时间限制的未来应用程序的实践,我想在单独的线程中运行数据捕获和处理.

I'm trying to make an application that collects data, processes it, displays it, and some actuation (open/close valves, etc). As a practice for future applications where I have some stricter time constraints, I want to run the data capture and processing in a separate thread.

我目前的问题是它告诉我无法从另一个线程启动计时器.

My current problem is that it's telling me I cannot start a timer from another thread.

当前代码进度

import sys
import PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QThread, pyqtSignal

# This is our window from QtCreator
import mainwindow_auto

#thread to capture the process data
class DataCaptureThread(QThread):
    def collectProcessData():
        print ("Collecting Process Data")
    #declaring the timer
    dataCollectionTimer = PyQt5.QtCore.QTimer()
    dataCollectionTimer.timeout.connect(collectProcessData)
    def __init__(self):
        QThread.__init__(self)

    def run(self):
        self.dataCollectionTimer.start(1000);

class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self) # gets defined in the UI file
        self.btnStart.clicked.connect(self.pressedStartBtn)
        self.btnStop.clicked.connect(self.pressedStopBtn)

    def pressedStartBtn(self):
        self.lblAction.setText("STARTED")
        self.dataCollectionThread = DataCaptureThread()
        self.dataCollectionThread.start()
    def pressedStopBtn(self):
        self.lblAction.setText("STOPPED")
        self.dataCollectionThread.terminate()


def main():
     # a new app instance
     app = QApplication(sys.argv)
     form = MainWindow()
     form.show()
     sys.exit(app.exec_())

if __name__ == "__main__":
     main()

任何有关如何使其工作的建议将不胜感激!

Any advice on how to get this to work would be appreciated!

推荐答案

你得把QTimer移到DataCaptureThread线程,另外,run方法结束时,线程被淘汰所以定时器被淘汰,所以你必须避免在不阻塞其他任务的情况下运行该函数.QEventLoop 用于此:

You have to move the QTimer to the DataCaptureThread thread, in addition to that when the run method ends, the thread is eliminated so the timer is eliminated, so you must avoid running that function without blocking other tasks. QEventLoop is used for this:

class DataCaptureThread(QThread):
    def collectProcessData(self):
        print ("Collecting Process Data")

    def __init__(self, *args, **kwargs):
        QThread.__init__(self, *args, **kwargs)
        self.dataCollectionTimer = QTimer()
        self.dataCollectionTimer.moveToThread(self)
        self.dataCollectionTimer.timeout.connect(self.collectProcessData)

    def run(self):
        self.dataCollectionTimer.start(1000)
        loop = QEventLoop()
        loop.exec_()

这篇关于PyQt5:线程中的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆