1

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.

cmannett85
  • 21,725
  • 8
  • 76
  • 119

1 Answers1

1

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.

user3427419
  • 1,769
  • 11
  • 15
  • You're right, it seems to be a regression. I've opened a bug here: https://bugreports.qt-project.org/browse/QTBUG-38181 – cmannett85 Apr 08 '14 at 08:40
  • This is not a bug, qt cancelled the support for this in QJSEngine: http://doc.qt.io/qt-5/qjsengine.html (search for Dynamic QObject Properties chapter) – jaba Jan 29 '18 at 16:45