首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用动画更改QWidget的背景色

使用动画更改QWidget的背景色
EN

Stack Overflow用户
提问于 2015-12-23 23:58:17
回答 1查看 8.8K关注 0票数 8

我想用动画改变小部件的背景色(比如qlabel)。事实上,我想运行淡入和淡出动画的背景颜色的子小部件在QMainWindow上。因此,我编写了如下新代码:

代码语言:javascript
运行
复制
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();

但是没有任何变化!

我该怎么做呢?

谢谢:-)

它解决了:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-24 00:53:03

经过一番调查之后,似乎从QVariantAnimation继承的QPropertyAnimation并不支持将QString作为动画的属性。所有支持的属性列表为这里 (Int,UInt,Double,Float,QLine,QLineF,QPoint,QPointF,QSize,QSizeF,QRect,QRectF,QColor)

因此,您需要对要更改背景色的每个小部件进行子类,并为它们创建自己的属性。

就像这个- Q_PROPERTY(QColor color READ color WRITE setColor)

在这个子类的setColor方法中,您应该更改颜色。

下面是QLabel的示例:

代码语言:javascript
运行
复制
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
  }
};

你对动画的呼吁应该改为:

代码语言:javascript
运行
复制
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->标签为AnimatedLabel (在表单设计器中将您的QLabel提升为AnimatedLabel )。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34445507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档