Change the background color of a QWidget using animation

I want to change the background color of widgets (e.g. qlabel) using animation. In fact, I want to run fade in and fade out the animation for the background color of the child widgets in QMainWindow. So, I wrote some codes, as shown 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 were no changes !!!
How can i do this?

Thanks: -)


He decided: -)

+4
source share
1 answer

After a little research, it seems that QVariantAnimationfrom which it is inherited QPropertyAnimationdoes not support QStringas a property of the animation. A list of all supported properties is here (Int, UInt, Double, Float, QLine, QLineF, QPoint, QPointF, QSize, QSizeF, QRect, QRectF, QColor)

, , .

- Q_PROPERTY(QColor color READ color WRITE setColor)

setColor .

QLabel :

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
  }
};

:

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

ui- > label - AnimatedLabel ( QLabel AnimatedLabel .

+5

Source: https://habr.com/ru/post/1621543/


All Articles