Qt QPropertyAnimation不';行不通

Qt QPropertyAnimation不';行不通,qt,Qt,我正在尝试在Qt桌面应用程序中测试动画。我只是从“帮助”中复制了一个示例。单击按钮后,新按钮仅出现在左上角,没有动画(即使结束位置错误)。我错过什么了吗 Qt 5.0.1,Linux Mint 64位,GTK #include "mainwindow.h" #include "ui_mainwindow.h" #include <QPropertyAnimation> MainWindow::MainWindow(QWidget *parent) : QMainWindow

我正在尝试在Qt桌面应用程序中测试动画。我只是从“帮助”中复制了一个示例。单击按钮后,新按钮仅出现在左上角,没有动画(即使结束位置错误)。我错过什么了吗

Qt 5.0.1,Linux Mint 64位,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();
}
#包括“mainwindow.h”
#包括“ui_main window.h”
#包括
主窗口::主窗口(QWidget*父窗口):
QMainWindow(父级),
用户界面(新用户界面::主窗口)
{
用户界面->设置用户界面(此);
}
MainWindow::~MainWindow()
{
删除用户界面;
}
void主窗口::在按钮上单击()
{
QPushButton*按钮=新的QPushButton(“动画按钮”,此按钮);
按钮->显示();
QPropertyAnimation动画(按钮,“几何体”);
动画。设置持续时间(10000);
设置起始值(QRect(0,0,100,30));
setEndValue(QRect(25025010030));
animation.start();
}

编辑:已解决。动画对象必须作为全局引用。例如,在private QPropertyAnimation*动画一节中。然后QPropertyAnimation=New(..)

你只是没有复制这个例子,你还做了一些改变,破坏了它。您的
动画
变量现在是一个局部变量,该变量在按下按钮时被销毁。将QPropertyImation实例作为MainWindow类的成员变量,并按如下方式使用:

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();
}

您不需要专门为删除
mAnimation
变量而设置插槽。如果您使用
QAbstractAnimation::DeleteWhenStopped
,Qt可以为您完成此任务:

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);

对我在你回答之前编辑了我的帖子;)但是你是对的,这是解决方案。这个解决方案不好:每次单击按钮按钮时,你都会动态创建一个动画,当你关闭应用程序时,当你删除析构函数中由
mAnimation
指向的动画时,最多会删除一个动画。因此,如果您多次单击,将出现内存泄漏。这个问题的最佳答案是