PyQt4 - 创建一个计时器

vix*_*enn 9 python timer pyqt

我很抱歉这个问题,但我已经阅读了很多东西,似乎我没有得到如何制作计时器.所以我发布了我的代码:

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())
Run Code Online (Sandbox Code Playgroud)

我试图让物体每200ms朝着它的目标前进.我试过没有自己它给了我同样的错误:

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'
Run Code Online (Sandbox Code Playgroud)

我不知道如何将计时器连接到带参数的函数.我以为我没有正确使用SLOT论证,但它给了我那些惊喜.我想这一切都是错的.我很感激一些帮助:)

Tim*_*ham 17

使用新式信号,它们更容易理解.

交换 -

QtCore.QTimer.connect(timer, QtCore.SIGNAL("timeout()"), self, QtCore.SLOT("func()"))
Run Code Online (Sandbox Code Playgroud)

随着 -

timer.timeout.connect(self.move_towards)   # assuming that move_towards is the handler
Run Code Online (Sandbox Code Playgroud)

一个简单但完整的工作计时器示例 -

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_()
Run Code Online (Sandbox Code Playgroud)

  • 如果它对您不起作用,那么您应该确保对存储的计时器的引用不是垃圾收集,并且还将一个小部件作为父级传递给计时器,这应当防止在退出作用域时过早收集垃圾. (3认同)