QPropertyAnimation 是 Qt 中一个用于控制 QObject 对象属性的动画类,它可以实现对目标对象进行平滑过渡的动画效果。QPropertyAnimation 可以控制任何继承自 QObject 的对象的属性,包括 QWidget、QGraphicsItem 等。
使用 QPropertyAnimation 需要经过以下步骤:
- 创建 QPropertyAnimation 对象,指定动画的目标对象和属性。
QPropertyAnimation *animation = new QPropertyAnimation(targetObj, "propertyName");
- 设置动画的起始值和结束值,可以使用 QVariant 类型来设置动画值,也可以使用指定类型的 setStartValue() 和 setEndValue() 函数。
animation->setStartValue(QVariant(fromValue));
animation->setEndValue(QVariant(toValue));
- 设置动画的时长和曲线。
animation->setDuration(durationMs);
animation->setEasingCurve(curveType);
- 开始动画。
animation->start();
例如,下面是一个将 QWidget 从原位置移动到目标位置的示例代码:
QPropertyAnimation *animation = new QPropertyAnimation(widget, "pos");
animation->setStartValue(QPoint(0, 0));
animation->setEndValue(QPoint(100, 100));
animation->setDuration(1000);
animation->setEasingCurve(QEasingCurve::OutQuad);
animation->start();
这个代码会将 widget 控件从左上角移动到 (100, 100) 的位置,动画时长为 1 秒,并使用 OutQuad 缓动曲线。