Question

I have a bunch of QRects and some text in a QGraphicsScene that I am trying to animate with QPropertyAnimation. Animating the text works fine but the QRects don't work because they fail to convert to a QGraphicsObject

This works perfectly

QPropertyAnimation *a = new QPropertyAnimation(this);
a->setTargetObject(items[size.x()*size.y()-1-aa]->toGraphicsObject()); //text
a->setPropertyName("pos");
a->setDuration(animationLength);
a->setStartValue(items[size.x()*size.y()-1-aa]->pos());
a->setEndValue(newTextPos);
a->setEasingCurve(easingCurve);
a->start(QAbstractAnimation::DeleteWhenStopped);

But this doesn't, because items[2*size.x()*size.y()-2-aa]->toGraphicsObject() returns a null pointer.

QPropertyAnimation *a = new QPropertyAnimation(this);
a->setTargetObject(items[2*size.x()*size.y()-2-aa]->toGraphicsObject()); //rect
a->setPropertyName("pos");
a->setDuration(animationLength);
a->setStartValue(items[2*size.x()*size.y()-2-aa]->pos());
a->setEndValue(newRectPos);
a->setEasingCurve(easingCurve);
a->start(QAbstractAnimation::DeleteWhenStopped);

Is there a way to fix this?

Was it helpful?

Solution

toGraphicsObject returns null pointer because QGraphicsRectItem is not a QGraphicsObject. You cannot use QGraphicsRectItem to perform an animation. I can suggest two workarounds:

  1. Create your own class derived from QObject and QGraphicsRectItem, create "pos" property and implement its getter and setter. See an example here.
  2. Create your own class derived from QGraphicsObject. Implement its boundingRect and paint pure virtual methods to make it paint a rectangle.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top