单次拍摄时间在 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 方法完成执行,线程将完成其执行,因此它被消除,因此计时器也会被消除。解决方案是保持运行方法运行,必须使用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_())

最新更新