在QJSEngine中访问动态属性

时间:2014-04-07 23:17:35

标签: c++ qt qjsengine

我可以访问传递到QObject的{​​{1}}的属性,但为什么我无法访问动态属性?

QJSEngine

返回:

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;

使用Qt 5.2。

1 个答案:

答案 0 :(得分:1)

似乎它可能是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中的一个错误,因为bahaviour与QScriptEngine不同。