Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTimer in QJSengine



  • hi,I want to add Qtimer to QJSengine, but something went wrong. I tried to create an object myself, it is possible to use the following method, but Qtimer does not work.
    jstimer.h

    #include <QObject>
    #include <QTimer>
    #include <QJSEngine>
    class JsTimer : public QObject
    {
        Q_OBJECT
    public:
        explicit JsTimer(QJSEngine* engine);
        ~JsTimer();
        void static registerToEngine(QJSEngine* jsengine);
    
        Q_INVOKABLE QJSValue createInstance();
    private:
        QJSEngine* m_engine;
    };
    
    

    jstimer.cpp

    #include "jstimer.h"
    #include <QDebug>
    JsTimer::JsTimer(QJSEngine *engine):QObject(engine)
    {
        qDebug()<<"create jstimer!";
    }
    
    JsTimer::~JsTimer()
    {
        qDebug()<<"delete jstimer!";
    }
    
    void JsTimer::registerToEngine(QJSEngine *jsengine)
    {
        if(jsengine==nullptr){
            return;
        }
        QJSValue factoryObj = jsengine->newQObject(new JsTimer(jsengine));
        jsengine->globalObject().setProperty("_timer", factoryObj);
    }
    
    QJSValue JsTimer::createInstance()
    {
        qDebug()<<"createInstance";
        return m_engine->newQObject(new QTimer());
    }
    
    

    main.cpp

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString fileName = ":/test.jst";
        QFile scriptFile(fileName);
        if (!scriptFile.open(QIODevice::ReadOnly)){
            qDebug()<<"open file fail!";
        }
        QTextStream stream(&scriptFile);
        QString contents = stream.readAll();
        scriptFile.close();
        QJSEngine myEngine;
        myEngine.installExtensions(QJSEngine::AllExtensions);
        JsTimer::registerToEngine(&myEngine);
        QJSValue result = myEngine.evaluate(contents, fileName);
        if (result.isError())
            qDebug()
                    << "Uncaught exception at line:"
                    << result.property("lineNumber").toInt()
                    << endl << result.toString();
        qDebug()<<"end";
        return a.exec();
    }
    

    test.jst

    print(_timer);
    var timer = _timer.createInstance();
    print("--------------");
    timer.timeout.connect(this,function(){
        print("timer out!");
    });
    timer.start(1000);
    

    Console printing

    create jstimer!
    js: JsTimer(0x1c6bcd38)
    createInstance
    

    error

    Error - RtlWerpReportException failed with status code :-1073741823. Will try to launch the process directly
    

Log in to reply