Search code examples
pythontimerpyqttimeout

PyQt4 - timer.timeout.connect() - cannot find reference


from PyQt4 import QtGui, QtCore
from code.pair import Pair
from code.breadth_first_search import breadth_first_search
import functools

class Ghosts(QtGui.QGraphicsPixmapItem):

    def __init__(self, name):
        super(Ghosts, self).__init__()

        self.set_image(name)

    def chase(self, goal):
        pos = Pair(self.x(), self.y())
        path = breadth_first_search(pos, goal)

        func = functools.partial(self.move_towards, path)
        timer = QtCore.QTimer()
        timer.timeout.connect(func)
        timer.start(700)

    def move_towards(self, path):
        print("in")
        if path.empty():
            return
        goal = path.get_nowait()
        self.setPos(goal.first(), goal.second())

When I type this it tells me timer.timeout.connect() - cannot find reference, this should resolve but doesn't and nothing happens when I run it. Then I try QtCore.QTimer.singleShot(700, func) instead of the timer above and it works perfecly but executes only once (as it should). Everything I tried to make a timer that executes many times fails. Please help.


Solution

  • You made a very common mistake. Nothing holds a link to your timer, so it gets deleted after chaise function ends. Replace timer with self.timer.