首页 > 解决方案 > 如何使用 QTimeLine 类在 C++ 中重写 QML 时间线?

问题描述

我已经用 Qt Design Studio 创建了这个时间线,它运行良好,但是因为我想用 C++ 控制时间线,所以我需要使用QTimeLine 类

Timeline {
    id: timeline
    animations: [
        TimelineAnimation {
            id: timelineAnimation
            duration: 1000
            loops: 0
            running: true
            to: 1000
            from: 0
        }
    ]
    endFrame: 1000
    startFrame: 0
    enabled: true
    KeyframeGroup {
        target: image
        property: "scale"
        Keyframe {
            value: 1.25
            frame: 100
        }
        Keyframe {
            value: 1
            frame: 1000
        }
    }
}

所以我像这样暴露了图像的比例属性。

#ifndef SCALER_H
#define SCALER_H

#include <QObject>
#include <QTimeLine>
#include <qqml.h>

class Scaler: public QObject{

    Q_OBJECT
    Q_PROPERTY(QVariant scale READ scale WRITE setScale NOTIFY scaleChanged)
    QVariant m_scale;

public:
    using QObject::QObject;
    QVariant scale() const{
        return m_scale;
    }

public slots:
    void setScale(QVariant scale){
        if (m_scale == scale)
            return;
        m_scale = scale;
        emit scaleChanged(m_scale);
    }

signals:
    void scaleChanged(QVariant scale);
};

#endif // SCALER_H

将物业与

engine.rootContext()->setContextProperty("scaler", &scaler);

并将 scale 属性更改为 scaler.scaler

Image {
    id: img1
    x: 139
    y: 46
    width: 159
    height: 234
    source: "images/image.svg"
    scale: scaler.scale
    fillMode: Image.PreserveAspectFit
    }

到目前为止,这有效。现在我需要使用 QTimeLine 类提供的 API 重写上面动画的 QML 版本。使用这个例子,我可以无休止地放大图像,但我没有看到设置关键帧等的方法。你怎么做呢?我可以触发我已经在 QML 中创建的时间线吗?

Scaler scaler;
timeline = new QTimeLine(1000, engine.rootContext());
timeline->setFrameRange(0, 100);
QObject::connect(timeline, &QTimeLine::frameChanged, &scaler, &scaler::setScale);
timeline->start();

标签: c++qmltimeline

解决方案


推荐阅读