Skip to main content
 首页 » 编程设计

python之QT 定时器不调用函数

2025年05月04日17lexus

我将 PyQt 与 Python3 结合使用。

我的 QTimer 没有调用它们被告知要连接的函数。 isActive() 正在返回 True,并且 interval() 工作正常。下面的代码(独立运行)演示了这个问题:线程已成功启动,但 timer_func() 函数从未被调用。大多数代码是样板 PyQT。据我所知,我正在按照文档使用它。它在一个带有事件循环的线程中。有什么想法吗?

import sys 
from PyQt5 import QtCore, QtWidgets 
 
class Thread(QtCore.QThread): 
    def __init__(self): 
        QtCore.QThread.__init__(self) 
 
    def run(self): 
        thread_func() 
 
 
def thread_func(): 
    print("Thread works") 
    timer = QtCore.QTimer() 
    timer.timeout.connect(timer_func) 
    timer.start(1000) 
    print(timer.remainingTime()) 
    print(timer.isActive()) 
 
def timer_func(): 
    print("Timer works") 
 
app = QtWidgets.QApplication(sys.argv) 
thread_instance = Thread() 
thread_instance.start() 
thread_instance.exec_() 
sys.exit(app.exec_()) 

请您参考如下方法:

您正在从线程的 run 方法中调用 thread_func,这意味着您在该函数中创建的计时器存在于该线程的事件循环中。要启动线程事件循环,您必须调用它的 exec_() 方法 from within it's run method ,不是来自主流。在此处的示例中,app.exec_() 永远不会执行。要使其工作,只需将 exec_ 调用移动到线程的 run 中。

另一个问题是当 thread_func 完成时,您的计时器会被销毁。为了让它保持活力,您必须在某处保留一个引用。

import sys 
from PyQt5 import QtCore, QtWidgets 
 
class Thread(QtCore.QThread): 
    def __init__(self): 
        QtCore.QThread.__init__(self) 
 
    def run(self): 
        thread_func() 
        self.exec_() 
 
timers = [] 
 
def thread_func(): 
    print("Thread works") 
    timer = QtCore.QTimer() 
    timer.timeout.connect(timer_func) 
    timer.start(1000) 
    print(timer.remainingTime()) 
    print(timer.isActive()) 
    timers.append(timer) 
 
def timer_func(): 
    print("Timer works") 
 
app = QtWidgets.QApplication(sys.argv) 
thread_instance = Thread() 
thread_instance.start() 
sys.exit(app.exec_())