2

I can not figure out how to organize the dynamic creation of the c++ objects in QJSEngine

I try to do so :

main.cpp

#include <QCoreApplication>
#include <QQmlEngine>
#include <QObject>
#include <QQmlComponent>
#include <QtQml>
#include <QQmlEngine>
#include "js_object.h"

Q_DECLARE_METATYPE(Js_Object*)

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QJSEngine myEngine;
    qmlRegisterType<Js_Object>("Js_Object", 1, 0, "Js_Object");
    QJSValue v=myEngine.evaluate("import Js_Object 1.0;\n var t= new  Js_Object() ;");
    qDebug()<<v.toString();
    return a.exec();
}

JsObject.h

#ifndef JS_OBJECT_H
#define JS_OBJECT_H

#include <QObject>
class Js_Object : public QObject
{
    Q_OBJECT
public:
    explicit Js_Object(QObject *parent = 0) : QObject(parent) {
        qDebug()<<"Js_Object::Js_Object(QObject *parent) : QObject(parent)";
}
};
#endif // JS_OBJECT_H

this example compile, bun console print :

"SyntaxError: Syntax error"

What I do wrong ?

QScriptEngine allow to do this, but in QT5.5 QScriptEngine is deprecated, try to work with QJSEngine

  • I think that you are mixing QML import statement and ECMAScript code. AFAIR, import statement is not in the standard of ECMAScript and is not supported. You probably should create QML code with required Javascript inside. – Kakadu Jun 09 '16 at 11:51
  • I just use a factory function. Maybe that will help you? Something like this: `engine.globalObject().setProperty("_factory",engine.newQObject(new Factory));` Then in the JS: `_factory.create()` This is the most predictable path, I've found. – Sohail Jun 10 '16 at 12:56
  • in QScriptEngine I can do QScriptValue ctor = ScriptEngine->newFunction([](QScriptContext *ctx, QScriptEngine *engine) -> QScriptValue { ScriptFile *o; o = new ScriptFile(ctx); return engine->newQObject(o, QScriptEngine::ScriptOwnership); }); QScriptValue metaObject = ScriptEngine->newQMetaObject(&QObject::staticMetaObject, ctor); ScriptEngine->globalObject().setProperty("TextFile", metaObject); and then in JS var f = new TextFile("1.txt"); look for analog in QJSEngine – alexander_8901 Jun 14 '16 at 13:38

0 Answers0