Python 3.x PyQt5-QTimer的问题

Python 3.x PyQt5-QTimer的问题,python-3.x,pyqt5,qtimer,Python 3.x,Pyqt5,Qtimer,您好,我有这个代码,我希望在给定的时间内,使用QTimer中断时,我不知道发生了什么,但函数finish从未调用过 import sys from PyQt5 import QtCore, QtWidgets import time class Thread(QtCore.QThread): def __init__(self): super().__init__() self.tiempo = True def run(self):

您好,我有这个代码,我希望在给定的时间内,
使用QTimer中断时,我不知道发生了什么,但函数
finish
从未调用过

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_())

run
方法和
finish
方法在不同的线程中。试着这样做:

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_())