我有一个派生自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();
}
QPropertyAnimation没有看到多边形属性,所以我在标题中定义了属性,如:
Q_PROPERTY(QPolygonF多边形READ polygonNew WRITE setPolygonNew) PolygonNew和setPolygonNew调用QGraphicsPolygonItem类的polygon()和setPolygon()。
结果动画开始但不起作用,我不确定它是否应该适用于多边形项目。在动画的开头,multipNew被调用三次,完全不调用setPolygonNew。有没有人对如何使其发挥作用有想法?
答案 0 :(得分:1)
QPolygonF
不是QPropertyAimation
支持的类型。您可以看到supported types here。
您必须提供自己的插值功能才能使其与QPolygonF
一起使用。
以下是Qt docs提供的示例:
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;
}