문제

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?

도움이 되었습니까?

해결책

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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top