c++qtqjsengine

Access dynamic property in QJSEngine


I can access properties of QObjects passed into a QJSEngine, but why can't I access dynamic properties?

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;

Returns:

4.2
35
0

Using Qt 5.2.


Solution

  • Seems it may be a bug in QML. If you use QScriptEngine instead, the problem seems to go away,

    #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;
    }
    

    results in

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

    Therefore this looks like a bug in QJSEngine as the bahaviour differs from QScriptEngine.