Qt 图形视图框架4-动画、碰撞检测和图形项组

  • [1. 动画](#1. 动画)
    • [1.1. 使用 QObject 包装器](#1.1. 使用 QObject 包装器)
    • [1.2. 属性动画(QPropertyAnimation)](#1.2. 属性动画(QPropertyAnimation))
    • [1.3. 定时器动画(QTimer)](#1.3. 定时器动画(QTimer))
    • [1.4. 场景推进动画(QGraphicsScene::advance)](#1.4. 场景推进动画(QGraphicsScene::advance))
  • [2. 碰撞检测](#2. 碰撞检测)

1. 动画

在Qt图形视图框架中,实现动画效果有多种常用方法,下面介绍几种主要方式:

以下是在Qt 5.15.5 (MinGW环境)中实现图形视图框架动画的常用方法,代码已亲测可正常运行:

1.1. 使用 QObject 包装器

创建一个 QObject 派生类作为控制器,管理图形项的动画:

cpp 复制代码
// itemcontroller.h
#include <QObject>
#include <QTimer>
#include "myitem.h"

class ItemController : public QObject
{
    Q_OBJECT
public:
    explicit ItemController(MyItem *item, QObject *parent = nullptr);
    
    void startRotation(int interval = 30, qreal speed = 60.0);
    void stopRotation();

private slots:
    void updateRotation();

private:
    MyItem *targetItem;
    QTimer *rotationTimer;
    QTime lastUpdateTime;
    qreal rotationSpeed;
};

// itemcontroller.cpp
#include "itemcontroller.h"

ItemController::ItemController(MyItem *item, QObject *parent)
    : QObject(parent),
      targetItem(item),
      rotationTimer(new QTimer(this)),
      rotationSpeed(60.0)
{
    connect(rotationTimer, &QTimer::timeout, this, &ItemController::updateRotation);
}

void ItemController::startRotation(int interval, qreal speed)
{
    rotationSpeed = speed;
    lastUpdateTime.start();
    rotationTimer->start(interval);
}

void ItemController::stopRotation()
{
    rotationTimer->stop();
}

void ItemController::updateRotation()
{
    if (!targetItem) return;
    
    int elapsed = lastUpdateTime.elapsed();
    lastUpdateTime.restart();
    
    qreal angleDelta = rotationSpeed * elapsed / 1000.0;
    qreal currentAngle = targetItem->rotation();
    currentAngle = fmod(currentAngle + angleDelta, 360.0);
    
    targetItem->setRotation(currentAngle);
}

1.2. 属性动画(QPropertyAnimation)

通过修改图形项的属性实现平滑过渡,需注册属性:

直接在myItem.h中定义QGraphicsObject子类MyGraphicsObject。不能在使用QGraphicsItem,因为QGraphicsItem 并不继承自 QObject,因此不能直接使用 QPropertyAnimation 动画系统,因为动画系统依赖于 QObject 的属性系统和信号槽机制。

cpp 复制代码
#ifndef MYITEM_H
#define MYITEM_H

#include <QGraphicsItem>
#include <QObject>
#include <QPointF>
#include <QPainter>
#include <QPropertyAnimation>
#include <QGraphicsObject>
#include <QGraphicsObject>
#include <QPropertyAnimation>

class MyGraphicsObject : public QGraphicsObject {
    Q_OBJECT

    // 声明 position 属性
    Q_PROPERTY(QPointF position READ pos WRITE setPos)

public:
    MyGraphicsObject(QObject *parent = nullptr) : QGraphicsObject() {
        // 初始化动画
        posAnimation = new QPropertyAnimation(this, "position", this);
        posAnimation->setStartValue(QPointF(0, 0));
        posAnimation->setEndValue(QPointF(100, 100));
        posAnimation->setDuration(1000);
        posAnimation->start();
    }

    // 重写 boundingRect 和 paint 方法
    QRectF boundingRect() const override {
        return QRectF(-10, -10, 20, 20);
    }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {
        painter->drawRect(boundingRect());
    }

    // 实现 position 属性的读写方法
    QPointF pos() const {
        return QGraphicsObject::pos();
    }

    void setPos(const QPointF &position) {
        QGraphicsObject::setPos(position);
    }

private:
    QPropertyAnimation *posAnimation;
};
#endif // MYITEM_H

1.3. 定时器动画(QTimer)

通过定时器定期更新图形项状态:

cpp 复制代码
#ifndef MYITEM_H
#define MYITEM_H

#include <QGraphicsItem>
#include <QObject>
#include <QPointF>
#include <QPainter>
#include <QPropertyAnimation>
#include <QGraphicsObject>
#include <QGraphicsObject>
#include <QPropertyAnimation>
#include <QTimer>

class MyItem : public QGraphicsObject {
    Q_OBJECT

    // 声明 position 属性
    Q_PROPERTY(QPointF position READ pos WRITE setPos)

public:
    MyItem(QObject *parent = nullptr) : QGraphicsObject() {
        // ...已有初始化...
        currentAngle = 0;

        rotationTimer = new QTimer(this);
        connect(rotationTimer, &QTimer::timeout, this, &MyItem::updateRotation);
        rotationTimer->start(30); // 约30fps
    }

    // 重写 boundingRect 和 paint 方法
    QRectF boundingRect() const override {
        return QRectF(-10, -10, 20, 20);
    }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {
        painter->drawRect(boundingRect());
    }

    // 实现 position 属性的读写方法
    QPointF pos() const {
        return QGraphicsObject::pos();
    }

    void setPos(const QPointF &position) {
        QGraphicsObject::setPos(position);
    }


private slots:
    void updateRotation(){
        currentAngle += 2;
        if (currentAngle >= 360) currentAngle = 0;
        setRotation(currentAngle);
    }

private:
    QTimer *rotationTimer;
    qreal currentAngle;
};
#endif // MYITEM_H

1.4. 场景推进动画(QGraphicsScene::advance)

通过重写advance()函数实现批量动画:

cpp 复制代码
// myitem.h
// myitem.h
#include <QGraphicsItem>
#include <QPainter>
#include <QTime>

class MyItem : public QGraphicsItem
{
public:
    MyItem();
    QRectF boundingRect() const override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;

    void setRotationSpeed(qreal speed);

protected:
    void advance(int phase) override;

private:
    qreal rotationSpeed;
    QTime lastUpdateTime;
};

// myitem.cpp

cpp 复制代码
// myitem.cpp
#include "myitem.h"

QRectF MyItem::boundingRect() const
{
    return QRectF(-20, -10, 40, 20); // 设置边界矩形,可根据实际图形调整
}

void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)
    painter->setBrush(Qt::red); // 设置填充颜色为红色
    painter->drawEllipse(-20, -10, 40, 20); // 绘制圆形
}

MyItem::MyItem() : rotationSpeed(0)
{
    lastUpdateTime.start();
}

void MyItem::setRotationSpeed(qreal speed)
{
    rotationSpeed = speed;
    lastUpdateTime.restart();
}

void MyItem::advance(int phase)
{
    if (!phase) return; // phase=0是预计算阶段

    if (rotationSpeed != 0) {
        int elapsed = lastUpdateTime.elapsed();
        lastUpdateTime.restart();

        qreal angleDelta = rotationSpeed * elapsed / 1000.0;
        setRotation(rotation() + angleDelta);
    }
}

// main.cpp中添加定时器触发场景更新

cpp 复制代码
#include <QApplication>
#include <QTimer>
#include "myitem.h"
#include "myview.h"

int main(int argc,char*argv[])
{
    QApplication app(argc,argv);
    QGraphicsScene scene;
    scene.setSceneRect(-200,-150,400,300);

    MyItem *item =new MyItem;
    item->setPos(QPointF(0, 0));
    scene.addItem(item);

    MyView view;
    view.setScene(&scene);
    view.show();

    // 方法1: 使用控制器
    ItemController controller(item);
    controller.startRotation(30, 90.0); // 90度/秒
    
    // 方法2: 使用属性动画
    // item->startRotationAnimation(5000); // 5秒转一圈
    
    // 方法3: 使用advance()
    // item->setRotationSpeed(60.0); // 60度/秒

    // 启动场景更新定时器
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, &scene, &QGraphicsScene::advance);
    timer.start(16); // 约60FPS

    return  app.exec();
}

效果:

2. 碰撞检测

tationSpeed(60.0); // 60度/秒

cpp 复制代码
    // 启动场景更新定时器
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, &scene, &QGraphicsScene::advance);
    timer.start(16); // 约60FPS

    return  app.exec();

效果:

2. 碰撞检测

---待更新

相关推荐
碧海蓝天20225 分钟前
C++法则21:避免将#include放在命名空间内部。
开发语言·c++
兮动人12 分钟前
Java应用全链路故障排查实战指南:从系统资源到JVM深度诊断
java·开发语言·jvm
R-sz23 分钟前
导出word并且插入图片
开发语言·c#·word
CodeWithMe23 分钟前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
脑袋大大的41 分钟前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
Wy. Lsy1 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
Tanecious.2 小时前
C++--红黑树
开发语言·c++
Top`2 小时前
Java 泛型 (Generics)
java·开发语言·windows
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
如何使用Java WebSocket API实现客户端和服务器端的通信?
java·开发语言·websocket
Shartin2 小时前
Can201-Introduction to Networking: Application Layer应用层
服务器·开发语言·php