QPropertyAnimation not working

I am trying to test the animation in a Qt desktop application. I just copied the example from the help. After clicking the button, the new button just appears in the upper left corner without animation (even the end position is incorrect). Did I miss something?

Qt 5.0.1, Linux Mint 64bit, GTK

#include "mainwindow.h" #include "ui_mainwindow.h" #include <QPropertyAnimation> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QPushButton *button = new QPushButton("Animated Button", this); button->show(); QPropertyAnimation animation(button, "geometry"); animation.setDuration(10000); animation.setStartValue(QRect(0, 0, 100, 30)); animation.setEndValue(QRect(250, 250, 100, 30)); animation.start(); } 

Edit: Resolved. The animation object should be like a global reference. For example, in the QPropertyAnimation * private animation section. Then QPropertyAnimation = New (....);

+4
source share
2 answers

You just did not copy this example, you also made some changes that violated it. Your animation variable is now a local variable that is destroyed at the end of the on_pushButton_clicked function. Make the QPropertyAnimation instance a member variable of the MainWindow class and use it as follows:

 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), mAnimation(0) { ui->setupUi(this); QPropertyAnimation animation } MainWindow::~MainWindow() { delete mAnimation; delete ui; } void MainWindow::on_pushButton_clicked() { QPushButton *button = new QPushButton("Animated Button", this); button->show(); mAnimation = new QPropertyAnimation(button, "geometry"); mAnimation->setDuration(10000); mAnimation->setStartValue(QRect(0, 0, 100, 30)); mAnimation->setEndValue(QRect(250, 250, 100, 30)); mAnimation->start(); } 
+4
source

You do not need to make a slot specifically to remove the mAnimation variable. Qt can do this for you if you use QAbstractAnimation::DeleteWhenStopped :

 QPropertyAnimation *mAnimation = new QPropertyAnimation(button, "geometry"); mAnimation->setDuration(10000); mAnimation->setStartValue(QRect(0, 0, 100, 30)); mAnimation->setEndValue(QRect(250, 250, 100, 30)); mAnimation->start(QAbstractAnimation::DeleteWhenStopped); 
+9
source

All Articles