gpt4 book ai didi

c++ - 在 QJSEngine 中访问动态属性

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:26 25 4
gpt4 key购买 nike

我可以访问传递给 QJSEngineQObject 的属性,但为什么我不能访问动态属性?

auto myObject = new MyObject(); // Contains a single property 'myProp'.

QJSEngine engine;

auto scriptMyObject = engine.newQObject( myObject );
engine.globalObject().setProperty( "myObject" , scriptMyObject );

engine.evaluate( "myObject.myProp = 4.2" );
cout << engine.evaluate( "myObject.myProp" ).toNumber() << endl;

myObject->setProperty( "newProp", 35 );
cout << myObject->property( "newProp" ).toInt() << endl;

cout << engine.evaluate( "myObject.newProp" ).toInt() << endl;

返回:

4.2
35
0

使用 Qt 5.2。

最佳答案

看来这可能是 QML 中的错误。如果您改用 QScriptEngine,问题似乎就消失了,

#include <QScriptEngine>
#include <QCoreApplication>
#include <QDebug>

int main(int a, char *b[])
{
QCoreApplication app(a,b);
auto myObject = new QObject;
QScriptEngine engine;

auto scriptMyObject = engine.newQObject( myObject );

myObject->setProperty( "newProp", 35 );
engine.globalObject().setProperty( "myObject" , scriptMyObject );
qDebug() << myObject->property( "newProp" ).toInt();
qDebug() << engine.evaluate( "myObject.newProp" ).toInteger();
qDebug() << engine.evaluate( "myObject.newProp = 45" ).toInteger();
qDebug() << myObject->property( "newProp" ).toInt();
qDebug() << " -------- ";
// still can't create new properties from JS?
qDebug() << engine.evaluate( "myObject.fancyProp = 30" ).toInteger();
qDebug() << myObject->property("fancyProp").toInt();

return 0;
}

结果

35
35
45
45
--------
30
0

因此这看起来像是 QJSEngine 中的错误,因为行为与 QScriptEngine 不同。

关于c++ - 在 QJSEngine 中访问动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22924829/

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