Evgenii Legotckoi
Nov. 18, 2018, 8:52 p.m.

Qt/C++ - Tutorial 086. Using QSequentialAnimationGroup and QPropertyAnimation to move a button

Let's write a small example of an application in which a button will be moved using property animations. To do this, we use the QSequentialAnimationGroup and QPropertyAnimation classes.

QSequentialAnimationGroup is a class that combines several animations into one group, which allows you to automatically start one animation when the previous QPropertyAnimation has completed.

Animation will be launched by pressing the button and this button will move in the window as shown in the image.


We will create the project by default in Qt Creator, and all changes will apply only to the Widget class. You will need to add a QPushButton button through a graphic designer.

Widget.h

And here is an example in the code

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. #include <QSequentialAnimationGroup>
  7.  
  8. namespace Ui {
  9. class Widget;
  10. }
  11.  
  12. class Widget : public QWidget
  13. {
  14. Q_OBJECT
  15.  
  16. public:
  17. explicit Widget(QWidget *parent = nullptr);
  18. ~Widget();
  19.  
  20. private slots:
  21. void onClickButton();
  22.  
  23. private:
  24. Ui::Widget *ui;
  25.  
  26. // Button animation group
  27. QSequentialAnimationGroup* animationGroup;
  28. };
  29.  
  30. #endif // WIDGET_H

Widget.cpp

The important point is that we create QPropertyAnimation with an indication of the property that we want to animate. In this case, it is "geometry". A property can be animated if it is declared in a class as Q_PROPERTY. Then smooth change of values of this property is performed.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. #include <QPropertyAnimation>
  5. #include <QDebug>
  6.  
  7. Widget::Widget(QWidget *parent) :
  8. QWidget(parent),
  9. ui(new Ui::Widget)
  10. {
  11. ui->setupUi(this);
  12.  
  13. // Create an animation group
  14. animationGroup = new QSequentialAnimationGroup(this);
  15.  
  16. // Create an animation of the motion property from left-top to right-top.
  17. QPropertyAnimation* leftTopToRightTop = new QPropertyAnimation(ui->pushButton, "geometry");
  18. leftTopToRightTop->setDuration(1000); // Animation duration
  19. leftTopToRightTop->setStartValue(ui->pushButton->geometry()); // Starting position and animation geometry
  20. leftTopToRightTop->setEndValue(ui->pushButton->geometry().translated(100, 0)); // End position and geometry of animation
  21. animationGroup->addAnimation(leftTopToRightTop); // Add animation to the group
  22.  
  23. // Right-top Bottom-right
  24. QPropertyAnimation* rightTopToRightBottom = new QPropertyAnimation(ui->pushButton, "geometry");
  25. rightTopToRightBottom->setDuration(1000);
  26. rightTopToRightBottom->setStartValue(leftTopToRightTop->endValue());
  27. rightTopToRightBottom->setEndValue(leftTopToRightTop->endValue().toRect().translated(0, 100));
  28. animationGroup->addAnimation(rightTopToRightBottom);
  29.  
  30. // Bottom right to left down
  31. QPropertyAnimation* rightBottomToLeftBottom = new QPropertyAnimation(ui->pushButton, "geometry");
  32. rightBottomToLeftBottom->setDuration(1000);
  33. rightBottomToLeftBottom->setStartValue(rightTopToRightBottom->endValue());
  34. rightBottomToLeftBottom->setEndValue(rightTopToRightBottom->endValue().toRect().translated(-100, 0));
  35. animationGroup->addAnimation(rightBottomToLeftBottom);
  36.  
  37. // Left-bottom top-left
  38. QPropertyAnimation* leftBottomToLeftTop = new QPropertyAnimation(ui->pushButton, "geometry");
  39. leftBottomToLeftTop->setDuration(1000);
  40. leftBottomToLeftTop->setStartValue(rightBottomToLeftBottom->endValue());
  41. leftBottomToLeftTop->setEndValue(rightBottomToLeftBottom->endValue().toRect().translated(0, -100));
  42. animationGroup->addAnimation(leftBottomToLeftTop);
  43.  
  44. // We connect button pressing to the slot to the button handler.
  45. connect(ui->pushButton, &QPushButton::clicked, this, &Widget::onClickButton);
  46. }
  47.  
  48. Widget::~Widget()
  49. {
  50. delete ui;
  51. }
  52.  
  53. void Widget::onClickButton()
  54. {
  55. // Run the animation
  56. animationGroup->start();
  57. }

Conclusion

Thus, it is possible to configure the most varied animations for object properties, which are marked with the Q_PROPERTY macro and have set and get methods.

Git Repository Link

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
  • ИМ
    Oct. 5, 2024, 4:51 p.m.
    Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
  • d
    July 5, 2024, 8:02 p.m.
    Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…