我有一个类是从QGraphicsPolygonItem派生的。里面有一个负责动画的函数。函数如下所示:
void DrawBase::makeAnimation(){
/* creating 2 states */
QState* st1 = new QState();
QState* st2 = new QState();
st1->addTransition(this, SIGNAL(clicked()), st2);
st2->addTransition(this, SIGNAL(clicked()), st1);
/* adding states to state machine */
_stateMachine.addState(st1);
_stateMachine.addState(st2);
_stateMachine.setInitialState(st1);
QObject::connect(st1, SIGNAL(entered()), this, SLOT(animate1()));
QObject::connect(st2, SIGNAL(entered()), this, SLOT(animate2()));
/* starting machine */
_stateMachine.start();
}
连接槽animate1()和animate2()如下:
void DrawBase::animate1()
{
qDebug() << "Animation 1";
animation = new QPropertyAnimation(this, "polygon");
animation->setDuration(1000);
animation->setStartValue(this->polygon());
QTransform trans;
trans=trans.scale(0.5,0.5);
QPolygonF newPoly=trans.map(this->polygon());
animation->setEndValue(newPoly);
animation->setEasingCurve(QEasingCurve::OutBounce);
animation->start();
}
Polygon属性没有被QPropertyAnimation看到,所以我在header中定义了这个属性:
Q_PROPERTY (QPolygonF polygon READ polygonNew WRITE setPolygonNew)PolygonNew和setPolygonNew调用QGraphicsPolygonItem类的polygon()和setPolygon()。
作为结果动画开始但不工作,我不确定它是否应该为多边形项目工作。在动画的开始polygonNew被调用了三次,setPolygonNew根本没有被调用。有人知道我该怎么做吗?
QPolygonF
不支持QPropertyAimation
的类型。您可以在这里看到支持的类型。
您必须提供自己的插值函数才能使其与QPolygonF
一起工作。
下面是Qt文档提供的一个例子:
QVariant myColorInterpolator(const QColor &start, const QColor &end, qreal progress)
{
...
return QColor(...);
}
...
qRegisterAnimationInterpolator<QColor>(myColorInterpolator);
下面是如何使用QPolygonF
:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
Q_PROPERTY(QPolygonF polygon READ getPolygon WRITE setPolygon)
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setPolygon(QPolygonF polygon);
QPolygonF getPolygon() const;
private:
Ui::MainWindow *ui;
QPolygonF poly;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPropertyAnimation>
QVariant myPolygonInterpolator(const QPolygonF &start, const QPolygonF &end, qreal progress)
{
if(progress < 1.0)
return start;
else
return end;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qRegisterAnimationInterpolator<QPolygonF>(myPolygonInterpolator);
poly << QPoint(10,0);
QPropertyAnimation *animation = new QPropertyAnimation(this, "polygon");
animation->setDuration(1000);
QPolygonF start;
start << QPoint(0, 0);
animation->setStartValue(start);
QPolygonF end;
end << QPoint(100, 100);
animation->setEndValue(end);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setPolygon(QPolygonF polygon)
{
poly = polygon;
}
QPolygonF MainWindow::getPolygon() const
{
return poly;
}