PDA

View Full Version : Animated Child Widget



elemings
17th May 2012, 21:17
I have the following simple little widget:

7736
7735

Works fine as a top-level widget. As a child widget though, it doesn't work.

What's wrong with it? Any help appreciated.

amleto
17th May 2012, 22:50
the problem is you're using (actually, abusing) the palette .




#if !defined ANIMATED_SQUARE_H
# define ANIMATED_SQUARE_H

# include <QtGui/QPalette>
# include <QtGui/QWidget>

#include <QVariant>

class QPropertyAnimation;

/**
* A square that transitions from one color to another.
*/
class AnimatedSquare
: public QWidget
{
Q_OBJECT

Q_PROPERTY (QColor animColor
READ animColor WRITE setAnimColor)
Q_PROPERTY (int animDuration
READ animDuration WRITE setAnimDuration)

public:

AnimatedSquare (QWidget* = 0);
~AnimatedSquare();

QSize minimumSizeHint() const;
QSize sizeHint() const;

void setAnimColors (const QColor&, const QColor&);
QColor animColor() const;
void setAnimColor (const QColor&);
int animDuration() const;
void setAnimDuration (int);

void start();

protected:

void paintEvent (QPaintEvent*);

private:

QPropertyAnimation* animation;
int duration;

QVariant m_val;
};

inline QSize
AnimatedSquare::minimumSizeHint() const
{
return QSize (50, 50);
}

inline QSize
AnimatedSquare::sizeHint() const
{
return minimumSizeHint();
}

inline QColor
AnimatedSquare::animColor() const
{
return m_val.value<QColor>();
}

inline int
AnimatedSquare::animDuration() const
{
return duration;
}

inline void
AnimatedSquare::setAnimDuration (int milliseconds)
{
duration = milliseconds;
}

#endif // !defined ANIMATED_SQUARE_H





#include <QtCore/QPropertyAnimation>
#include <QtGui/QPainter>

#include <QPaintEvent>
#include <QColor>
#include <QDebug>

#include "AnimatedSquare.h"

AnimatedSquare::AnimatedSquare (QWidget* parent)
: QWidget (parent)
, animation (new QPropertyAnimation (this, "animColor"))
, duration (1000)
{
animation->setDuration(duration);
animation->setLoopCount (-1); // infinite
}

void AnimatedSquare::paintEvent(QPaintEvent* e)
{
QPainter painter (this);
QColor c;
if(m_val.canConvert<QColor>())
c = m_val.value<QColor>();

painter.fillRect(rect(), c);
}

void AnimatedSquare::setAnimColors (const QColor& begin, const QColor& end)
{
animation->setStartValue(begin);
animation->setEndValue(end);
}

void AnimatedSquare::start()
{
animation->start();
}

void AnimatedSquare::setAnimColor (const QColor& newColor)
{
m_val = newColor;
update();
}

AnimatedSquare::~AnimatedSquare()
{
delete animation;
}