使用动画改变QWidget的背景颜色

8

我希望通过动画来改变小部件(如qlabel)的背景颜色。实际上,我想在QMainWindow上为子小部件的背景颜色运行淡入和淡出动画。因此,我编写了以下几行代码:

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();

但是没有任何更改!!!
我该怎么做?

谢谢 :-)


问题已解决 :-)

1个回答

18
经过一番调查,似乎QPropertyAnimation继承自QVariantAnimation,后者不支持QString作为动画属性。所有支持的属性列表在这里(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。


对不起,我在C++和Qt方面是个初学者。你能给我一个例子吗?非常感谢 :-) - Samson Davidoff
@SamsonDavidoff,我已更新答案,欢迎来到stackoverflow,请接受答案如果它回答了你的问题。 - Shf
我可以对QLabel的pixmap属性做动画效果吗?也就是说,使用动画来改变QLabel的pixmap。 - Samson Davidoff
这个答案完全解决了我的问题,但我有一个小问题。我们如何使用这个过程来为 border-color 添加动画效果?我尝试了两个小时来实现它,但是我找不到任何解决方案!! - Saeed Masoomi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接