实现气泡漂浮效果
一、环境
qt5.14.2,mingw64
二、主要逻辑
新建一个类继承widget,重写paintEvent 弄上图片。创建定时器,触发动画效果。
动画部分,获取父窗口大小后,在此范围内随机生成x,y位置。
(注:虽然可以直接用生成的位置,但是移动看起来非常生硬。用了动画之后看起来比较自然流畅)
主界面,创建几个widget。
三、效果展示
四、源码
#ifndef BUBBLEWIDGET_H
#define BUBBLEWIDGET_H
#include <QWidget>
#include <QPainter>
#include <QPropertyAnimation>
#include <QRandomGenerator>
#include <QTimer>
#include <QPoint>
#include <QRect>
class BubbleWidget : public QWidget
{
Q_OBJECT
public:
explicit BubbleWidget(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
private slots:
void startAnimation();
signals:
private:
QTimer *timer;
QPixmap pixmap;
};
#endif // BUBBLEWIDGET_H
#include "BubbleWidget.h"
#include <QSequentialAnimationGroup>
BubbleWidget::BubbleWidget(QWidget *parent) : QWidget(parent)
{
setFixedSize(50,50);
//
pixmap = QPixmap("C:/Users/13729/Pictures/buble3.png");
// 设置定时器
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &BubbleWidget::startAnimation);
timer->start(4000); // 每隔5秒启动一次动画(根据需要调整)
startAnimation();
}
void BubbleWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(0, 0, pixmap.scaled(size()));
}
void BubbleWidget::startAnimation()
{
// 获取父窗口的大小
QRect parentRect = parentWidget()->rect();
// 创建动画
QPropertyAnimation *animationX = new QPropertyAnimation(this, "pos");
animationX->setDuration(5000); // 动画持续时间为5秒
animationX->setStartValue(pos());
animationX->setEndValue(QPoint(QRandomGenerator::global()->bounded(parentRect.width() - width()),
QRandomGenerator::global()->bounded(parentRect.height() - height())));
// 创建动画序列
QSequentialAnimationGroup *animationGroup = new QSequentialAnimationGroup(this);
animationGroup->addAnimation(animationX);
animationGroup->setLoopCount(-1); // 无限循环
// 启动动画
animationGroup->start();
}
#c++新特性##qt##气泡漂浮#
智元机器人成长空间 174人发布
查看22道真题和解析