Javascript 函数作为从 c++ 定义的 QML 属性
Javascript function as QML property defined from c++
我在 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
做了类似的事情:
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 会提供默认函数实现。
该函数用于允许用户返回给定输入值的自定义文本:
text: control.textFromValue(control.value, control.locale)
以文档中的示例为例,以下是分配/覆盖函数的方法:
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
}
}
相关文章:
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 如何将带有自定义对象的容器从C++传递到QML
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 自定义 QML QQuick彩绘项目成员锚点未在 qml 中设置为父级
- 基于 QML 模型的组件在 android 上具有未定义的 modelData
- 当在基类中定义枚举时,qml中的Q_ENUM未定义值
- Qt - 定义 QML 的全局函数
- 当通过引用传递 QObject 时,C++信号的参数在 QML 中显示为"未定义"
- QML自定义列表数据类型
- Javascript 函数作为从 c++ 定义的 QML 属性
- QML 引用错误 - <thing> 在 C++/QML 集成期间未定义
- 如何制作自定义C 类QML类型
- 将模块连接到 QML C++ - 引用错误: <blank> 未定义
- 从QT C 返回自定义对象,并在QML中打印属性
- 如何使用预先定义的状态创建自定义快速QML项目
- 如何在 c++ 中从文件创建自定义 QML 元素
- QML[未定义]错误
- QML:如何将动态创建的组件与自定义的内部对象一起使用
- qml扩展上的未定义符号(来自示例)
- 在 c++Function for QtCharts (ChartView) 中定义 qml 对象