Reputation: 1743
I am trying to use single shot timer inside QThread but it's not working. Following is the code I am using:
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
The problem I am facing is that after time out the timerPINNo function never gets called. The single shot is working when using normally but not when I am calling it from QThread. Where I am making mistake ?
Upvotes: 0
Views: 254
Reputation: 243973
The problem is caused because if the run method finishes executing the thread finishes its execution and therefore it is eliminated and consequently the timer also. The solution is to keep the run method running for it, QEventLoop
must be used.
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_())
Upvotes: 1