Daniel Vildosola
Daniel Vildosola

Reputation: 33

problems with PyQt5 QTimer

Hi I have this code and I want that in a given time the while breaks using a QTimer, I don't know what is happening but the function finish its never called

import sys
from PyQt5 import QtCore, QtWidgets
import time

class Thread(QtCore.QThread):
    def __init__(self):
        super().__init__()
        self.tiempo = True

    def run(self):
        timer = QtCore.QTimer()
        timer.timeout.connect(self.finish)
        timer.start(5000)
        while self.tiempo:
            print(timer.isActive())
            print("we are here")

    def finish(self):
        self.tiempo = False
        print("timer timeout")



app = QtWidgets.QApplication(sys.argv)
thread_instance = Thread()
thread_instance.start()
sys.exit(app.exec_())

Upvotes: 1

Views: 299

Answers (1)

S. Nick
S. Nick

Reputation: 13651

run method and finish method are in different threads. Try it like this:

import sys
from PyQt5 import QtCore, QtWidgets
#import time
import threading

class Thread(QtCore.QThread):
    def __init__(self):
        super().__init__()
        self.tiempo = True
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.finish)
        self.timer.start(3000)
        print(f'2 {threading.current_thread()}')

    def run(self):
#        self.timer = QtCore.QTimer()
#        self.timer.timeout.connect(self.finish)
#        self.timer.start(3000)
        print(f'4 {threading.current_thread()}')
        while self.tiempo:
            print(self.timer.isActive())
            print("we are here")
            self.msleep(500)

    def finish(self):
        print(f'3 {threading.current_thread()}')
        self.tiempo = False
        print("timer timeout")
        self.timer.stop()   # +++



app = QtWidgets.QApplication(sys.argv)
print(f'1 {threading.current_thread()}')

thread_instance = Thread()
thread_instance.start()

w = QtWidgets.QWidget()
w.show()

sys.exit(app.exec_())

enter image description here

Upvotes: 1

Related Questions