我想用动画改变小部件的背景色(比如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();
但是没有任何变化!
我该怎么做呢?
谢谢:-)
它解决了:)
发布于 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
的示例:
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->标签为AnimatedLabel (在表单设计器中将您的QLabel提升为AnimatedLabel )。
https://stackoverflow.com/questions/34445507
复制相似问题