Python PyQt4 - 创建一个计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32362340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PyQt4 - creating a timer
提问by vixenn
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:
我试图让物体每 200 毫秒向目标移动一次。我没有自我尝试它给了我同样的错误:
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 : )
我不知道如何将计时器连接到带参数的函数。我认为我没有正确使用 SLOT 参数,但它给了我这些迷惑。我想这都是错的。我很感激一些帮助:)
采纳答案by Tim Wakeham
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_()