gpt4 book ai didi

Javascript 函数作为从 C++ 定义的 QML 属性

转载 作者:行者123 更新时间:2023-11-30 01:08:23 27 4
gpt4 key购买 nike

我在 C++ 中定义了以下 QML 对象:

class MyObj : public QQuickItem {
Q_OBJECT
Q_PROPERTY(QVariant func MEMBER func)

public slots:
void callFunc(){
//Call function pointed by "func" somehow
}

private:
QVariant func;
};

在 QML 中,我使用 MyObj 如下:

MyObj{
func: function test(){ console.log("Hi!"); }

Button{
text: "Call func"
onClicked: parent.callFunc()
}
}

我收到以下错误:

Unable to assign a function to a property of any type other than var.

我不明白,难道 QVariant 属性不应该与 property var 相同吗?这样做的正确方法是什么?

最佳答案

您可以使用 QJSValue为了这。 Qt Quick Controls 2 的 SpinBox does 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
}
}

关于Javascript 函数作为从 C++ 定义的 QML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931696/

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