簡體   English   中英

一次射擊時間在pyqt4 QThread內部不起作用

[英]Single shot time not working inside pyqt4 QThread

我正在嘗試在QThread中使用單發計時器,但是它不起作用。 以下是我正在使用的代碼:

class thread1((QtCore.QThread):
    def __init__(self,parent):
        QtCore.QThread.__init__(self, parent)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print "Timer completed"

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
        else: pass

我面臨的問題是在超時后timerPINNo函數永遠不會被調用。 正常使用時,單拍有效,但當我從QThread調用時,單拍無效。 我在哪里犯錯?

引起該問題的原因是,如果run方法完成執行線程,則完成其執行,因此將其消除,因此計時器也將取消。 解決方案是使run方法保持運行狀態,必須使用QEventLoop

import sys
from PyQt4 import QtCore

class thread1(QtCore.QThread):
    def __init__(self,*args, **kwargs):
        QtCore.QThread.__init__(self, *args, **kwargs)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print("Timer completed")


    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
            loop = QtCore.QEventLoop()
            loop.exec_()

if __name__ == "__main__":
   app = QtCore.QCoreApplication(sys.argv)
   th = thread1()
   th.start()
   sys.exit(app.exec_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM