2013-10-21 38 views
1

我使用Python 2.7與PyQt 4.0。PyQt動畫QGraphicsItem不起作用

我想在動畫中將QGraphicsRectItem移動10 px。我已閱讀文檔和幾個教程,但我無法使其工作。我的代碼有什麼問題?

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
import random 

class TestWidget(QWidget): 
    def __init__(self, parent=None): 
     QWidget.__init__(self, parent) 
     self.scene = QGraphicsScene() 
     self.view = QGraphicsView(self.scene) 
     self.button1 = QPushButton("Do test") 
     self.button2 = QPushButton("Move forward 10") 

     layout = QVBoxLayout() 
     buttonLayout = QHBoxLayout() 
     buttonLayout.addWidget(self.button1) 
     buttonLayout.addWidget(self.button2) 
     buttonLayout.addStretch() 
     layout.addWidget(self.view) 
     layout.addLayout(buttonLayout) 
     self.setLayout(layout) 

     self.button1.clicked.connect(self.do_test) 
     self.button2.clicked.connect(self.move_forward) 

    def do_test(self): 
     self.turtle = self.scene.addRect(0,0,10,20) 

    def move_forward(self): 
     animation = QGraphicsItemAnimation() 
     timeline = QTimeLine(1000) 
     timeline.setFrameRange(0,100) 
     animation.setTimeLine(timeline) 
     animation.setItem(self.turtle) 
     animation.setPosAt(1.0, QPointF(self.turtle.x(),self.turtle.y()+10)) 
     timeline.start() 

感謝您的幫助!

回答

2

試試這個小小的變化(在函數move_forward中)。

animation = QGraphicsItemAnimation(self) 

改變行爲,我代替

animation = QGraphicsItemAnimation() 

3

您的示例不起作用的原因是您沒有保留對move_forward方法中創建的QGraphicsItemAnimation的引用,因此在它有機會做任何事情之前它會被垃圾收集。

我會建議你在__init__創建動畫,以便以後可以訪問它的實例屬性:

def __init__(self, parent=None): 
    ... 
    self.animation = QGraphicsItemAnimation() 

def move_forward(self): 
    timeline = QTimeLine(1000) 
    timeline.setFrameRange(0, 100) 
    self.animation.setTimeLine(timeline) 
    self.animation.setItem(self.turtle) 
    self.animation.setPosAt(
     1.0, QPointF(self.turtle.x(), self.turtle.y() + 10)) 
    timeline.start()