#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_animation = new QPropertyAnimation(ui->label, "geometry");
startAnimation();
}
MainWindow::~MainWindow()
{
delete ui;
delete m_animation;
}
void MainWindow::startAnimation()
{
m_animation->setDuration(3000);
m_animation->setKeyValueAt(0, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.25, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(0.5, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.75, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(1, QRect(50, 50, 128, 128));
m_animation->start();
}
我想多次显示startAnimation
函数中完成的动画,现在它只显示两次。我尝试使用QSequential
但这也不起作用。我也尝试将此函数与线程连接,但是当我创建线程类的对象时,它显示未解决的符号错误。
您应该设置 loopCount 属性。
void MainWindow::startAnimation()
{
m_animation->setLoopCount(10);
m_animation->setDuration(3000);
m_animation->setKeyValueAt(0, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.25, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(0.5, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.75, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(1, QRect(50, 50, 128, 128));
m_animation->start();
}
不,这里不需要线程。您所需要的只是QSequentialAnimationGroup
(正如我之前所说(。例如:
int numberOfLoops = 3;
QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this);
for(int i = 0; i < numberOfLoops; ++i)
{
QPropertyAnimation *m_animation = new QPropertyAnimation(this, "geometry");
m_animation->setDuration(3000);
m_animation->setKeyValueAt(0, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.25, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(0.5, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.75, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(1, QRect(50, 50, 128, 128));
group->addAnimation(m_animation);
}
group->start(QAbstractAnimation::DeleteWhenStopped);
但我仍然认为你现在的代码对我的方法有点错误,所以最终的代码是:
//type 3 and animation will repeat 3 time, type 10 and it will repeat 10 and so on
int numberOfLoops = 5;
QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this);
for(int i = 0; i < numberOfLoops; ++i)
{
QPropertyAnimation *m_animation = new QPropertyAnimation(this, "geometry");
m_animation->setDuration(1500);
m_animation->setKeyValueAt(0, QRect(50, 50, 128, 128));
m_animation->setKeyValueAt(0.5, QRect(200, 50, 128, 128));
m_animation->setKeyValueAt(1, QRect(50, 50, 128, 128));
group->addAnimation(m_animation);
}
group->start(QAbstractAnimation::DeleteWhenStopped);
也不要认为这段代码会产生内存泄漏,不!如您所见,我添加了QAbstractAnimation::DeleteWhenStopped
标志,这意味着您创建的所有QPropertyAnimation
对象也将被删除(当动画停止时(!为了证明您可以添加一行并运行应用程序,您将看到所有对象都将被删除(但这只是一个证明,例如release
应用程序中不需要这样做(:
//...
group->addAnimation(m_animation);
connect(m_animation,&QPropertyAnimation::destroyed,[](){qDebug()<< "m_animation destroyed";});
//...
但是我在这里使用了C++11
(CONFIG += c++11
.pro
文件(以及信号和插槽的新语法,但当然,如果需要,您可以使用旧语法。