将 QPropertyAnimation 应用于 QRect

Applying QPropertyAnimation to QRect

本文关键字:QRect 应用于 QPropertyAnimation      更新时间:2023-10-16

我创建了一个 QRect 对象

QRect ellipse(10.0 , 10.0 , 10.0 , 10.0);
QPainter painter(this);
painter.setBrush(Qt::red);
painter.drawEllipse(ellipse);

现在我想使用 QPropertyAnimation 对其进行动画处理,但由于它只能应用于 QObject 对象(据我所知(,我需要以某种方式将 QRect 转换为 QObject。有没有办法做到这一点?

无需创建类,您可以使用自己的小部件,必须添加新属性。

例:

小部件.h

#ifndef WIDGET_H
#define WIDGET_H
#include <QPaintEvent>
#include <QWidget>
class Widget : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(QRect nrect READ nRect WRITE setNRect)
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
    QRect nRect() const;
    void setNRect(const QRect &rect);
protected:
    void paintEvent(QPaintEvent *event);
private:
    QRect mRect;
};
#endif // WIDGET_H

小部件.cpp

#include "widget.h"
#include <QPainter>
#include <QPropertyAnimation>
Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    QPropertyAnimation *animation = new QPropertyAnimation(this, "nrect");
    //animation->setEasingCurve(QEasingCurve::InBack);
    animation->setDuration(1000);
    animation->setStartValue(QRect(0, 0, 10, 10));
    animation->setEndValue(QRect(0, 0, 200, 200));
    animation->start();
    connect(animation, &QPropertyAnimation::valueChanged, [=](){
        update();
    });
}
Widget::~Widget()
{
}
QRect Widget::nRect() const
{
    return mRect;
}
void Widget::setNRect(const QRect &rect)
{
    mRect = rect;
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QRect ellipse(mRect);
    QPainter painter(this);
    painter.setBrush(Qt::red);
    painter.drawEllipse(ellipse);
}

法典