gpt4 book ai didi

c++ - 将 QPropertyAnimation 应用于 QRect

转载 作者:行者123 更新时间:2023-11-28 05:11:27 27 4
gpt4 key购买 nike

我创建了一个 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。有办法吗?

最佳答案

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

例子:

widget.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);
}

code

关于c++ - 将 QPropertyAnimation 应用于 QRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43428627/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com