[Qt-interest] Best way to implement "onShow/onHide" animation when GraphicsItem gets added/removed from scene?

Carl Snellman carl.snellman at gmail.com
Fri Jul 23 00:47:39 CEST 2010


Hey,

I'm trying to implement an animation to a QGraphicsItem derivate, and
I'd like the animation to scale the item from 0 to 1 when the item is
added, and then when removed from scene, it would shrink away (scale
1->0). I got the "onShow" animation working fine, but "onHide" (or
onRemoval) causes me headaches. I tried the following:
>>>>>>>>>>>>>>>>>>>>>>>>
QVariant MyObject::itemChange(GraphicsItemChange change, const
QVariant &value) {
     if (change == QGraphicsItem::ItemVisibleChange && scene()) {
         bool visible = value.toBool();
         QPropertyAnimation * sizeAnimation = new
QPropertyAnimation(this, "scale");
         sizeAnimation->setDuration(700);
         sizeAnimation->setEasingCurve(QEasingCurve::OutBounce);
         if(visible) {
             qDebug() << "MyObject::itemChange onShow";
             setScale(0);
             sizeAnimation->setEndValue(1); // grow to normal size
         } else {
            qDebug() << "MyObject::itemChange onHide";
            sizeAnimation->setEndValue(0); // shrink away
         }
         sizeAnimation->setLoopCount(1);
         sizeAnimation->start();
     }
     return QGraphicsItem::itemChange(change, value);
 }
<<<<<<<<<<<<<<<<<<<<<<<<
As said, onShow anim is okay, but the ItemVisibleChange for hide never
happens if the object is removed from scene. So I tried the following:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
QVariant MyObject::itemChange(GraphicsItemChange change, const
QVariant &value) {
    if (change == QGraphicsItem::ItemSceneChange) {
        QPropertyAnimation * sizeAnimation = new
QPropertyAnimation(this, "scale");
        sizeAnimation->setDuration(700);
        sizeAnimation->setEasingCurve(QEasingCurve::OutBounce);
        if( ! value.isNull()) {
            qDebug() << "MyObject::itemChange onSceneAdd";
            setScale(0);
            sizeAnimation->setEndValue(1); // grow to normal size
        } else {
           qDebug() << "MyObject::itemChange onSceneRemove";
           sizeAnimation->setEndValue(0); // shrink away
        }
        sizeAnimation->setLoopCount(1);
        sizeAnimation->start();
    }
 }
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Again, onShow works fine, but when the item is removed from scene, it
gets the event with value non-null !??!?!
So looks like that won't work either as an approach.

Would anyone have any ideas how to implement such functionality? There
is also one more complication: I'd like to have the object
self-destruct when the animation is finished... Otherwise I'd need to
react on the anim finished() signal somewhere and delete the object
then. Any ideas how to implement self-destruct?

Carl



More information about the Qt-interest-old mailing list