单拍时间在pyqt4 QThread内部不起作用

时间:2017-11-17 12:14:08

标签: python python-2.7 pyqt 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呼叫时,则没有。我在哪里弄错了?

1 个答案:

答案 0 :(得分:1)

问题是由于如果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_())