Доступ к динамическому свойству в QJSEngine

Я могу получить доступ к свойствам QObjectс перешли в 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;

Возвращает:

4.2
35
0

Использование Qt 5.2.

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, так как поведение отличается от QScriptEngine.

1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]