Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color of QWidget using animation

Tags:

qt

I want to change background color of widgets (like qlabel) using animation. In fact, I want to run fade in and fade out animation for background color of child widgets on QMainWindow. So, I wrote afew codes as below:

QPropertyAnimation *animation = new QPropertyAnimation(ui->label1, "styleSheet");

animation->setStartValue("background-color: rgb(240, 240, 240)");
animation->setEndValue("background-color: rgb(126, 194, 66)");
animation->setDuration(3000);

animation->start();

But there was no changes!!!
How can I do it?

Thanks :-)


It solved :-)

like image 662
Samson Davidoff Avatar asked Dec 23 '15 23:12

Samson Davidoff


1 Answers

After a bit of investigation, it seems that QVariantAnimation from which QPropertyAnimation is inherited from does not support QString as property for animations. The list of all supported properties is here (Int,UInt,Double,Float,QLine,QLineF,QPoint,QPointF,QSize,QSizeF,QRect,QRectF,QColor)

So you would need to subclass every widget that you want to change background color and create your own property for them.

Like this one - Q_PROPERTY(QColor color READ color WRITE setColor)

and in setColor method of this subclass you should change color.

example for QLabel below:

class AnimatedLabel : public QLabel
{

  Q_OBJECT
  Q_PROPERTY(QColor color READ color WRITE setColor)

public:
  AnimatedLabel(QWidget *parent = 0)
  {
  }
  void setColor (QColor color){
    setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()));
  }
  QColor color(){
    return Qt::black; // getter is not really needed for now
  }
};

and your call for animation should change to:

QPropertyAnimation *animation = new QPropertyAnimation(ui->label, "color");
animation->setDuration(2000);
animation->setStartValue(QColor(0, 0, 0));
animation->setEndValue(QColor(240, 240, 240));
animation->start();

where ui->label is AnimatedLabel (promote your QLabel to AnimatedLabel in form designer.

like image 70
Shf Avatar answered Sep 20 '22 23:09

Shf