【问题标题】:PyQt5: Timer in a threadPyQt5:线程中的计时器
【发布时间】:2018-04-30 13:05:32
【问题描述】:

问题描述

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

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

当前代码进度

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

任何关于如何使它工作的建议都将不胜感激!

【问题讨论】:

    标签: python pyqt pyqt5 qthread qtimer


    【解决方案1】:

    您必须将 QTimer 移动到 DataCaptureThread 线程,此外,当 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_()
    

    【讨论】:

    • 谢谢!这在编辑行后有效:self.dataCollectionTimer.timeout.connect(self.collectProcessData)self.dataCollectionTimer.timeout.connect(lambda:self.collectProcessData) 否则会给出错误:TypeError: collectProcessData() takes 0 positional arguments but 1 was given 我不太明白,因为没有传递任何参数
    • @robotHamster 如果它对您有用,请不要忘记将我的答案标记为正确。
    • @ellyanesc 如果我将 lambda 添加到您的答案中可以吗?
    • def collectProcessData() 更改为def collectProcessData(self)
    • 更正:代码运行,但“收集过程数据”从未打印到控制台。在run 中启动计时器后,我立即添加了print ("Called Start"),并打印了@ellyanesc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多