I want to animate a QGraphicsPixmapItem
in my QGraphicsScene
, with QPropertyAnimation
.
QPixmap pixmap(filePath);
QGraphicsItem *pixmapItem = graphicsScene->addPixmap(pixmap);
QPropertyAnimation animation(pixmapItem, "x"); // here lies the problem
animation.setDuration(30000);
// ...
animation.start();
I checked the doc, so I already know that QGraphicsPixmapItem
and its parent QGraphicsItem
are no QObject
, and that a QPropertyAnimation
constructor with a QGraphicsItem
does not exist. According to various sources, the best way is to create a new class, e.g. AnimatedGraphicsItem
which inherits from QObject
and QGraphicsItem
OR I can simply inherit from QGraphicsObject
.
class AnimatedGraphicsItem : public QObject, public QGraphicsItem // or public QGraphicsObject
{
Q_OBJECT
Q_INTERFACES(QGraphicsItem) // not needed if I inherit from QGraphicsObject, right?
};
What do I need to include exactly in the header and source files of my AnimatedGraphicsItem
class? One source told me to include this in the header file too, but I thought, this is already inherited?
public:
AnimatedGraphicsItem(QGraphicsItem *parent = 0);
private:
virtual QRectF boundingRect() const;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
And how do I have to use my AnimatedGraphicsItem
class?
Do I have to cast my QGraphicsItem *pixmapItem
to AnimatedGraphicsItem
? (If yes, how?) Do I have to create a new instance of AnimatedGraphicsItem
?
I haven't found a good example on the Internet.
Thanks in advance!
Okay, got it.
I had to instantiate my AnimatedGraphicsItem
object, then setPixmap
, setFlag
, … and addItem
to my scene (and it was important to use new
).