单次拍摄时间在 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 调用时无效。我哪里出错了?

问题的产生是因为如果运行方法完成执行,线程完成执行,因此它被消除,因此计时器也被消除。解决方法就是为它保留运行方法运行ning,必须使用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_())