您可以为此使用QJSValue。 Qt Quick Controls 2的SpinBoxdoes something similar:
Q_PROPERTY(QJSValue textFromValue READ textFromValue WRITE setTextFromValue NOTIFY textFromValueChanged FINAL)
它的 getter 和 setter 是这样实现的:
QJSValue QQuickSpinBox::textFromValue() const
{
Q_D(const QQuickSpinBox);
if (!d->textFromValue.isCallable()) {
QQmlEngine *engine = qmlEngine(this);
if (engine)
d->textFromValue = engine->evaluate(QStringLiteral("function(value, locale) { return Number(value).toLocaleString(locale, 'f', 0); }"));
}
return d->textFromValue;
}
void QQuickSpinBox::setTextFromValue(const QJSValue &callback)
{
Q_D(QQuickSpinBox);
if (!callback.isCallable()) {
qmlInfo(this) << "textFromValue must be a callable function";
return;
}
d->textFromValue = callback;
emit textFromValueChanged();
}
如果没有给出,getter 会提供一个默认的函数实现(或者该值实际上不是一个函数)。
函数is used 允许用户为给定的输入值返回自定义文本:
text: control.textFromValue(control.value, control.locale)
以documentation 为例,以下是您分配/覆盖函数的方式:
SpinBox {
id: spinbox
from: 0
value: 110
to: 100 * 100
stepSize: 100
anchors.centerIn: parent
property int decimals: 2
property real realValue: value / 100
validator: DoubleValidator {
bottom: Math.min(spinbox.from, spinbox.to)
top: Math.max(spinbox.from, spinbox.to)
}
textFromValue: function(value, locale) {
return Number(value / 100).toLocaleString(locale, 'f', spinbox.decimals)
}
valueFromText: function(text, locale) {
return Number.fromLocaleString(locale, text) * 100
}
}