我想用动画改变小部件的背景颜色(如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();
Run Code Online (Sandbox Code Playgroud)
但没有变化!
我该怎么做?
谢谢 :-)
它解决了:-)
经过一些调查后,似乎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
}
};
Run Code Online (Sandbox Code Playgroud)
你的动画调用应改为:
QPropertyAnimation *animation = new QPropertyAnimation(ui->label, "color");
animation->setDuration(2000);
animation->setStartValue(QColor(0, 0, 0));
animation->setEndValue(QColor(240, 240, 240));
animation->start();
Run Code Online (Sandbox Code Playgroud)
其中ui-> label是AnimatedLabel(在表单设计器中将QLabel提升为AnimatedLabel.
| 归档时间: |
|
| 查看次数: |
5287 次 |
| 最近记录: |