PyQt5 QTimer 的问题

problems with PyQt5 QTimer

你好,我有这段代码,我希望 while 在给定时间内使用 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_())