PDA

View Full Version : Moving a QGraphicsItem by using QPropertyAnimation



Rabbitl96l
1st April 2015, 07:10
I am planning to move a circle in the graphics view but it doesn't work. Here is my source code:

circle.h

#ifndef CIRCLE_H
#define CIRCLE_H
#include <QGraphicsItem>
#include <QPainter>

class Circle : public QObject, public QGraphicsItem
{
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
public:
Circle();
~Circle();
QRectF boundingRect() const;
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};

#endif // CIRCLE_H
dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>
#include <QPropertyAnimation>
#include "circle.h"

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
Q_OBJECT

public:
explicit Dialog(QWidget *parent = 0);
~Dialog();

private:
Ui::Dialog *ui;
QGraphicsScene *scene;
Circle *circle;
QPropertyAnimation *animation;
};

#endif // DIALOG_H
circle.cpp

#include "circle.h"

Circle::Circle()
{

}

Circle::~Circle()
{

}

QRectF Circle::boundingRect() const
{
return QRectF(20, 100, 50, 50);
}

void Circle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rect = boundingRect();
QPen pen(Qt::NoPen);
QBrush brush(Qt::blue);
brush.setStyle(Qt::SolidPattern);

painter->setPen(pen);
painter->setBrush(brush);
painter->drawEllipse(rect);
}
dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);

circle = new Circle;
scene->addItem(circle);

animation = new QPropertyAnimation(circle, "geometry", NULL);
animation->setDuration(5000);
animation->setEndValue(QRect(500, 100, 150, 150));

animation->start();
}

Dialog::~Dialog()
{
delete ui;
}

Can anyone please tell me how to solve this thing? Thanks in advance. :D

anda_skoa
1st April 2015, 07:49
Your property is called "pos" .
You are trying to animate non existant property "geometry"

Cheers,
_

Kryzon
1st April 2015, 08:03
Neither QObject nor QGraphicsItem seem to have the 'geometry' property you're assigning to that animation controller. So it's not defined anywhere, and this is probably why nothing happens.

The documentation specifies the properties of QObject-based classes:
http://doc.qt.io/qt-5/qobject.html
http://doc.qt.io/qt-5/qgraphicsitem.html

So in your case you will probably have to write something like this:

Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry)

void setGeometry( QRectF& newRect )
{
geometry = newRect // Copy.
setPos( newRect.topLeft() );
}

QRectF boundingRect()
{
return geometry;
}
Also, make sure you're only using QRectF values (for example in the 'setEndValue' function).