PyQt5:线程中的计时器

2024-10-01 15:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

问题描述

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

我当前的问题是它告诉我不能从另一个线程启动计时器。在

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()

如有任何建议,如何使这一工作将不胜感激!在


Tags: the数据fromimportselfinitdefconnect
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:13

您必须将QTimer移到DataCaptureAread线程,此外,当run方法结束时,线程将被消除,计时器也将被消除,因此您必须避免在不阻塞其他任务的情况下运行该函数。QEventLoop用于:

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_()

相关问题 更多 >

    热门问题