Qt creates an animated button

Qt creates an animated button

In this blog, we will learn how to create an animated button using Qt. We will use the QPropertyAnimation class, which allows us to control the animation of any property of an object.

Step 1 - Create Button

First, we need to create a QPushButton object to represent our animated button. We can use the following code:

QPushButton *button = new QPushButton("Click me", parent);

This will create a QPushButton object with the text "Click me" and add it to the specified parent QWidget object.

Step 2 - Set animation properties for the button

Next, we need to set properties for the buttons so that we can change them via animation. In this example, we will animate the size and color properties of the button. We can use the following code:

QPropertyAnimation *animation = new QPropertyAnimation(button, "geometry");
animation->setDuration(1000);
animation->setStartValue(QRect(0, 0, 100, 30));
animation->setEndValue(QRect(250, 250, 200, 60));
animation->setEasingCurve(QEasingCurve::InOutQuad);
animation->start();

Here we create a QPropertyAnimation object, then connect it to the button and set its properties to the geometry. We also set the animation duration to 1000 milliseconds, the start and end values ​​to the initial and final positions of the button (the values ​​here are rectangular areas whose size and position we can set), and the animation curve to QEasingCurve::InOutQuad, To give the animation a smooth effect. Finally we call the start() function to start the animation.

Step 3 - Run the program

Now we can run the program and click the button to watch its animation! The complete Qt program code should look like this:

#include <QPushButton>
#include <QPropertyAnimation>
#include <QEasingCurve>

int main(int argc, char *argv[])
{
    
    
    QApplication app(argc, argv);

    QWidget *parent = new QWidget;
    parent->setFixedSize(500, 500);

    QPushButton *button = new QPushButton("Click me", parent);
    button->setGeometry(0, 0, 100, 30);

    QPropertyAnimation *animation = new QPropertyAnimation(button, "geometry");
    animation->setDuration(1000);
    animation->setStartValue(QRect(0, 0, 100, 30));
    animation->setEndValue(QRect(250, 250, 200, 60));
    animation->setEasingCurve(QEasingCurve::InOutQuad);
    animation->start();

    parent->show();
    return app.exec();
}

Congratulations, you have learned how to create an animated button with Qt!

Guess you like

Origin blog.csdn.net/qq_25549309/article/details/131643830