QPropertyAnimation不起作用

时间:2013-03-22 21:30:09

标签: qt

我正在尝试在Qt桌面应用程序中测试动画。我刚刚从帮助中复制了示例。单击按钮后,新按钮只显示在左上角没有动画(甚至结束位置错误)。我错过了什么吗?

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

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

2 个答案:

答案 0 :(得分:9)

您不需要专门用于删除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);

答案 1 :(得分:6)

你刚才没有复制这个例子,你也做了一些破坏它的修改。您的animation变量现在是一个在on_pushButton_clicked函数末尾被销毁的局部变量。使QPropertyAnimation实例成为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();
}
相关问题