此答案仅适用于 NumberAnimation 对象。可能类似的方法也可以用于替换其他Animation 对象。
正如ddriver 已经指出的那样,除了变通之外别无他法。
这是我对问题的解决方案。它可能看起来很复杂,但我可以保证它很容易使用。在此答案的末尾,我使用此代码放置了指向示例项目源代码的链接。你可以试试看。
将这些文件添加到您的项目中:
#ifndef EASINGVALUEFORPROGRESS_H
#define EASINGVALUEFORPROGRESS_H
#include <QObject>
#include <QEasingCurve>
class EasingValueForProgress : public QObject
{
Q_OBJECT
public:
explicit EasingValueForProgress(QObject *parent = 0);
Q_INVOKABLE double getValue(int easingEnum, double progress){
QEasingCurve easing((QEasingCurve::Type)easingEnum);
return easing.valueForProgress(progress);
}
signals:
public slots:
};
#endif // EASINGVALUEFORPROGRESS_H
- easingvalueforprogress.cpp
#include "easingvalueforprogress.h"
EasingValueForProgress::EasingValueForProgress(QObject *parent) : QObject(parent)
{
}
import QtQuick 2.0
Item {
id: xValueAnimator
property Item target
property string targetProperty
property double from
property double to
property int easing: Easing.Linear
property double xValue
onXValueChanged: {
if (target.hasOwnProperty(targetProperty)) {
target[targetProperty] = calculateCurrentValue(
from, to, easing, xValue);
}
else
console.error("XValueAnimator: target:", target,
"does not have property", targetProperty)
}
function calculateCurrentValue(
defaultFrom, defaultTo, animationEasing, xValue) {
return defaultFrom + (defaultTo - defaultFrom)
* easingValueForProgress.getValue(animationEasing, xValue)
}
}
将此添加到您的 main.cpp:
#include <QQmlContext>
#include "easingvalueforprogress.h"
EasingValueForProgress easingValueForProgress;
engine.rootContext()->setContextProperty(
"easingValueForProgress", &easingValueForProgress);
现在你可以像这样使用它(而不是NumberAnimation对象):
XValueAnimator {
target: object_you_want_to_affect // for example id of the object
targetProperty: "property_to_affect" // for example "x"
from: 100
to: 500
easing: Easing.OutQuad // omit to use Easing.Linear
xValue: myXValue // your property holding values from 0 to 1
}
Here我提供了工作示例项目。欢迎下载并测试它。