QT定时器不能调用函数
问题描述:
我在Python3中使用PyQt。QT定时器不能调用函数
我的QTimer
s没有调用它们被告知要连接的功能。 isActive()
正在返回True
,而正在正常工作。下面的代码(独立工作)演示了这个问题:该线程已成功启动,但从不调用该函数。大部分代码是样板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_())
答
你打电话从withn你的线程的run
方法thread_func
,这意味着你的计时器在创建该函数住在该线程的事件循环。要启动线程事件循环,您必须将其称为exec_()
方法from within it's run method,而不是来自主thrad。在你的例子中,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_())
非常感谢!这解决了这个问题。也帮助我理解QT代码的结构总体上好一点。 –