1、概述
源码放在文章末尾
该项目基于QPropertyAnimation实现了控件平移动画和控件之间的相互覆盖效果,项目demo演示如下所示:
项目解析:
new QPropertyAnimation(ui.SingleOcclusion, “pos”); //创建动画对象,第一个参数传入需要移动的控件对象,第二个参数"pos"表示该控件实现直线移动。
信号槽表示动画移动结束会发送finished信号。
pPosAnimation1 = new QPropertyAnimation(ui.SingleOcclusion, "pos");
pBothPosAnimation1 = new QPropertyAnimation(ui.BothOcclusion, "pos");
connect(pPosAnimation1, &QPropertyAnimation::finished, this, &SlidingAnimation::OcclusionAnimation);
connect(pBothPosAnimation1, &QPropertyAnimation::finished, this, &SlidingAnimation::BothOcclusionAnimation);
控件左移动实现,右移动和双边移动同理
void SlidingAnimation::on_left_clicked()
{ui.BothOcclusion->hide();QTime time;time.start();while (time.elapsed() < 100){QCoreApplication::processEvents();_sleep(100);}//每次移动前先取消控件的透明度设置pButtonOpacity->setOpacity(1);ui.SingleOcclusion->setGraphicsEffect(pButtonOpacity);//这里的处理是因为布局中的控件在动画移动后如果界面发生改变会重新布局,这样移动//后的控件会回到原来的位置,这里是让控件移动结束后一直停留在移动后的位置QLayoutItem* item = ui.horizontalLayout_2->itemAt(3);if ((int)item->spacerItem() == (int)spacerLeft){ui.horizontalLayout_2->removeItem(spacerLeft);ui.horizontalLayout_2->insertWidget(3, ui.SingleOcclusion);}QRect line = ui.line_4->geometry();QRect label = ui.leftLabel->geometry();QRect widget = ui.SingleOcclusion->geometry();int difference = (widget.width() - label.width()) / 2;//设置动画移动时间pPosAnimation1->setDuration(1000);//设置动画开始移动的位置pPosAnimation1->setStartValue(QPoint(line.x() + line.width(), widget.y()));//设置动画移动结束的位置pPosAnimation1->setEndValue(QPoint(label.x() - difference, widget.y()));pPosAnimation1->setEasingCurve(QEasingCurve::InOutQuad);// 开始动画前移除widget,并添加占位符ui.horizontalLayout_2->removeWidget(ui.SingleOcclusion);ui.horizontalLayout_2->insertItem(3, spacerLeft);pPosAnimation1->start();
}
该函数为动画结束后信号触发的槽函数,主要实现的功能是当控件移动结束后覆盖到另一个控件的上方并设置该控件的透明度
void SlidingAnimation::OcclusionAnimation()
{QRect widget = ui.SingleOcclusion->geometry();ui.SingleOcclusion->move(widget.x(), widget.y());pButtonOpacity->setOpacity(1);ui.SingleOcclusion->setGraphicsEffect(pButtonOpacity);QPropertyAnimation* pOpacityAnimation1 = new QPropertyAnimation(pButtonOpacity, "opacity");pOpacityAnimation1->setDuration(600);pOpacityAnimation1->setStartValue(1);pOpacityAnimation1->setEndValue(0.3);pOpacityAnimation1->start();
}