Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

python - PyQt4 - creating a timer

I'm sorry for the question but I have read a bunch of things and it seems that I do not get how to make a timer. So I'm posting my code:

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)
        while not path.empty():
            aim = path.get_nowait()
            func = functools.partial(self.move_towards, aim)
            timer = QtCore.QTimer()
            QtCore.QTimer.connect(timer, QtCore.SIGNAL("timeout()"), self, QtCore.SLOT("func()"))
            timer.start(200)

    def move_towards(self, goal):
        self.setPos(goal.first(), goal.second())

I'm trying to make the object move towards its aim every 200ms. I tried without self it gives me the same errors:

QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'bytes'
QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'bytes'
QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 2 has unexpected type 'bytes'

I have no idea how to connect the timer to a function with arguments. I thought that I'm not using the SLOT argument right but it gave me those mystakes. I suppose that it is all wrong. I'd appreciate some help : )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use new style signals, they are easier to understand.

Swap -

QtCore.QTimer.connect(timer, QtCore.SIGNAL("timeout()"), self, QtCore.SLOT("func()"))

With -

timer.timeout.connect(self.move_towards)   # assuming that move_towards is the handler

A simple but full example of a working timer -

import sys

from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QApplication

app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)

def tick():
    print 'tick'

timer = QTimer()
timer.timeout.connect(tick)
timer.start(1000)

# run event loop so python doesn't exit
app.exec_()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...