Dynamic c++ object in QJSEngine

2019-07-24 23:44发布

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

标签: c++ qt qml qt5
0条回答
登录 后发表回答