如何同时为两个QLabel运行时长不同的QGraphicsOpacityEffect
实现两个QLabel同步启动不同时长的透明度动画
核心思路
用QParallelAnimationGroup管理两个独立的QPropertyAnimation,分别绑定到两个QLabel的QGraphicsOpacityEffect的opacity属性上。并行动画组会让所有子动画同时启动,各自按照设置的时长完成动画,完全满足同步启动但时长不同的需求。
具体代码实现
#include <QApplication> #include <QWindow> #include <QLabel> #include <QGraphicsOpacityEffect> #include <QPropertyAnimation> #include <QParallelAnimationGroup> #include <QVBoxLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWindow window; QWidget *centralWidget = new QWidget(&window); QVBoxLayout *layout = new QVBoxLayout(centralWidget); // 创建两个QLabel QLabel *label1 = new QLabel("Label 1 (时长2秒)", centralWidget); QLabel *label2 = new QLabel("Label 2 (时长5秒)", centralWidget); layout->addWidget(label1); layout->addWidget(label2); // 为label1创建透明度效果和动画 QGraphicsOpacityEffect *opacity1 = new QGraphicsOpacityEffect(label1); label1->setGraphicsEffect(opacity1); QPropertyAnimation *anim1 = new QPropertyAnimation(opacity1, "opacity"); anim1->setDuration(2000); // 2秒时长 anim1->setStartValue(1.0); anim1->setEndValue(0.0); anim1->setLoopCount(-1); // 无限循环,可选,根据需求调整 // 为label2创建透明度效果和动画 QGraphicsOpacityEffect *opacity2 = new QGraphicsOpacityEffect(label2); label2->setGraphicsEffect(opacity2); QPropertyAnimation *anim2 = new QPropertyAnimation(opacity2, "opacity"); anim2->setDuration(5000); // 5秒时长 anim2->setStartValue(1.0); anim2->setEndValue(0.0); anim2->setLoopCount(-1); // 无限循环,可选 // 用并行动画组管理两个动画,实现同步启动 QParallelAnimationGroup *animGroup = new QParallelAnimationGroup; animGroup->addAnimation(anim1); animGroup->addAnimation(anim2); // 启动动画 animGroup->start(); window.setCentralWidget(centralWidget); window.resize(300, 200); window.show(); return a.exec(); }
关键说明
QParallelAnimationGroup的作用就是让所有加入的动画同时触发,每个动画独立控制自己的时长、插值曲线等参数,完全不需要线程相关操作,线程方案反而会复杂化。- 如果需要动画结束后反转(比如从透明变回不透明),可以给每个动画添加
QSequentialAnimationGroup,把正向和反向动画串起来,再加入并行组。 - 动画的
setLoopCount可以设置循环次数,-1表示无限循环,按需调整即可。
内容的提问来源于stack exchange,提问作者mazelover1939
相关产品推荐
相关产品推荐

