Search code examples
qtqt5qpushbuttonqt6qpropertyanimation

How to create a simple animated button in Qt?


I don't understand the syntax of QPropertyAnimation at all, I looked at several "similar" questions, but I couldn't figure it out.

Could you write a simple example of a button that, when pressed, will gradually reduce its width to zero, so that one icon remains from it, and after pressing it again, it returns to its previous width.

I read the QPropertyAnimation documentation, but it seemed too incomprehensible to me, and I couldn't figure out the questions on the forum where this method also appeared.


Solution

  • In the doc https://doc.qt.io/qt-6/qpropertyanimation.html you have a similar example where the position changes. I do not clearly see what confusion there can be. QPropertyAnimation animates the property of an object from a start value to an end value.

    QPushButton *button = new QPushButton(tr("Animated Button"), this);
    QPropertyAnimation *anim = new QPropertyAnimation(button, "pos", this);
    anim->setDuration(10000);
    anim->setStartValue(QPoint(0, 0));
    anim->setEndValue(QPoint(100, 250));
    anim->start();
    

    Apparently, width is a property of QPushButton, which it inherits from QWidget: https://doc.qt.io/qt-6/qwidget.html#width-prop. So, from the example in the doc, you can simply replace the three values prop, start value and end value.