【问题标题】:How to animate the outline of a QGraphicsItem in real time?如何实时为 QGraphicsItem 的轮廓设置动画?
【发布时间】:2015-07-30 18:47:26
【问题描述】:

我正在用 Qt 设计一个计时器。使用 QGraphicsEllipseItem,我画了一个圆圈,现在我需要每秒围绕这个圆圈为 QPen 设置动画(改变颜色)。我找到了 QGraphicsPathItem,但我需要一些关于如何前进的示例。谁能给我举个例子?

【问题讨论】:

    标签: qt qgraphicsview qgraphicsitem


    【解决方案1】:

    你有两个问题:

    1. QGraphicsEllipseItem 不是QObject 所以QPropertyAnimation 不能直接用在这个项目上
    2. QGraphicsItemAnimation 不包括您要设置动画的属性。

    你能做什么?
    IMO 最好的方法是提供一些自定义的QObject,你可以在上面做这个动画。您可以继承QObject 或使用假的QGraphicsObject(即QObject)。

    class ShapeItemPenAnimator : public QGraphicsObject {
        Q_OBJECT
    private:
        QAbstractGraphicsShapeItem *mParent;
        QPropertyAnimation *mAnimation;
    
    public:
        QPROPERTY(QColor penColor
                  READ penColor
                  WRITE setPenColor)
    
        explicit ShapeItemPenAnimator(QAbstractGraphicsShapeItem * parent)
        : QGraphicsObject(parent)
        , mParent(parent) {
           setFlags(QGraphicsItem::ItemHasNoContents);
           mAnimation = new QPropertyAnimation(this, "penColor", this);
        }
    
        QColor penColor() const {
            return mParent->pen().color();
        }
    public slots:
        void setPenColor(const QColor &color) {
             QPen pen(mParent->pen());
             pen.setColor(color);
             mParent->setPen(pen);
        }
    
    public:
        void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {
        }
    
        QRectF boundingRect() const {
             return QRectF();
        }
    
        QPropertyAnimation *animation() const {
            return mAnimation;
        }
    }
    

    现在您只需将此对象附加到您的 QGraphicsEllipseItem 并设置您需要的动画。

    // yourEllipse
    ShapeItemPenAnimator *animator = new ShapeItemPenAnimator(yourEllipse);
    animator->animation()->setEndValue(....);
    animator->animation()->setStartValue(....);
    animator->animation()->setDuration(....);
    animator->animation()->setEasingCurve(....);
    

    【讨论】:

    • 感谢您的宝贵时间。我试图理解 Qt 中的整个图形。很抱歉,如果我问任何蹩脚的问题。现在我只是想运行你的例子,看看会发生什么。所以我将 QGraphicsEllipseItem 传递给 ShapeItemPenAnimator 并得到这个错误,“抽象类的无效新表达式”......
    • 只是实现缺少的方法。可能是boindingRect.
    • 嗨,属性动画,动画是预定义的,然后我们开始它。在这里,在这种情况下,我不明白它是如何工作的?我在 setTargetObject() 中传递了 graphicsview 对象,对吗?
    • ShapeItemPenAnimator 只是可以公开属性的代理对象,因为它是QObject。它不做任何其他事情。就像我写的那样,您可以继承 QObject 并获得相同的结果,但在这种情况下,内存管理更加困难(这就是我使用 QGraphicsObject 的原因)。关于属性动画阅读其文档。这个setTarget我写错了它不应该在那里(我已经修复了)。
    • 谢谢。我会检查:)
    【解决方案2】:

    Qt 中有几个类可以帮助处理 QGraphicsItem 的动画。我建议调查QGraphicsItemAnimationQPropertyAnimation。您可以使用第二个动画项目的颜色。这是使用 QPropertyAnimation 的示例: How to make Qt widgets fade in or fade out?

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 2015-07-06
      • 1970-01-01
      • 2021-09-24
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多