Search code examples
pythonpyqt5qtimer

Why QTimer doesn't work in a object? python PyQt


I'm new to python and pyqt. I just figured out that QTimer need eventloop running to work.

Why doesn't this work?

import PyQt5.QtCore
import sys


app = PyQt5.QtCore.QCoreApplication(sys.argv)

class Foo:
    def __init__(self):
        self.timer = PyQt5.QtCore.QTimer()
        self.timer.timeout.connect(lambda: print("foo"))
        self.timer.start(500)

Foo()

app.exec_()

This works fine on the other hand.

import PyQt5.QtCore
import sys


app = PyQt5.QtCore.QCoreApplication(sys.argv)

timer = PyQt5.QtCore.QTimer()
timer.timeout.connect(lambda: print("foo"))
timer.start(500)

app.exec_()

Solution

  • Create an instance of the class foo = Foo()

    Foo -> <class '__main__.Foo'>
    foo -> <__main__.Foo object at 0x0000000002AD8A90>
    

    import PyQt5.QtCore
    import sys
    
    
    app = PyQt5.QtCore.QCoreApplication(sys.argv)
    
    class Foo:
        def __init__(self):
            self.timer = PyQt5.QtCore.QTimer()
            self.timer.timeout.connect(lambda: print("foo"))
            self.timer.start(500)
    
    print(f'Foo -> {Foo}')
    foo = Foo()
    print(f'foo -> {foo}')
    
    app.exec_()