【问题标题】:QT Timers not calling functionQT 定时器不调用函数
【发布时间】:2013-07-10 22:21:12
【问题描述】:

我将 PyQt 与 Python3 一起使用。

我的QTimers 没有调用他们被告知要连接的函数。 isActive() 正在返回 Trueinterval() 工作正常。下面的代码(独立工作)演示了问题:线程已成功启动,但从未调用过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_())

【问题讨论】:

    标签: python multithreading qt python-3.x pyqt5


    【解决方案1】:

    您从线程的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_())
    

    【讨论】:

    • 非常感谢!这解决了问题。也帮助我更好地理解了 QT 代码结构。
    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多