定时器无法连接到pyqt5中的插槽 [英] the timer can not be connected to the slot in pyqt5
问题描述
我无法将计时器连接到 move() 插槽timer.timeout.connect(self.move)
这不起作用但是 QtCore.QTimer.singleShot(50, self.move)
这只是工作一步而已.
I can not connect the timer to the move() slot
timer.timeout.connect( self.move)
this is not working
but QtCore.QTimer.singleShot(50, self.move)
this is just working one step not more.
class Bullet(QGraphicsRectItem):
def __init__(self):
super().__init__()
self.setRect(0,0,10,50)
#timer = QTimer()
#timer.timeout.connect( self.move)
#timer.start(50)
QtCore.QTimer.singleShot(50, self.move)
def move(self):
print("Timer Clicked")
self.setPos(self.x(), self.y()-10)
推荐答案
问题很简单,在函数中创建的变量是局部变量,函数执行完毕后会被消除,因此信号没有触发,而是QTimer.singleShot()
有一个全局作用域,解决办法是扩展定时器的作用域,为此你必须让它成为类的成员.
the problem is simple, a variable created in a function is local and will be eliminated when the function is finished, therefore the signal does not fire, instead the QTimer.singleShot()
has a global scope, the solution is to extend the scope of the timer, for this you must make it a member of the class.
class Bullet(QGraphicsRectItem):
def __init__(self):
super().__init__()
self.setRect(0,0,10,50)
self.timer = QTimer()
self.timer.timeout.connect(self.move)
self.timer.start(50)
def move(self):
print("Timer Clicked")
self.setPos(self.x(), self.y()-10)
这篇关于定时器无法连接到pyqt5中的插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!