What is the equivalent of JavaScript's setTimeout on qtScript?

后端 未结 5 1258
清酒与你
清酒与你 2021-01-04 11:18

Not much to add; what is the equivalent of JavaScript\'s setTimeout on qtScript?

5条回答
  •  醉梦人生
    2021-01-04 11:29

    You can expose the QTimer as an instantiable class to the script engine. You can then instantiate it via new QTimer().

    This is documented in Making Applications Scriptable.

    Below is a complete example. The timer fires a second after the script is evaluated, prints timeout on the console, and exits the application.

    // https://github.com/KubaO/stackoverflown/tree/master/questions/script-timer-11236970
    #include 
    
    template  void addType(QScriptEngine * engine) {
       auto constructor = engine->newFunction([](QScriptContext*, QScriptEngine* engine){
          return engine->newQObject(new T());
       });
       auto value = engine->newQMetaObject(&T::staticMetaObject, constructor);
       engine->globalObject().setProperty(T::staticMetaObject.className(), value);
    }
    
    int main(int argc, char ** argv) {
       QCoreApplication app{argc, argv};
    
       QScriptEngine engine;
       addType(&engine);
       engine.globalObject().setProperty("qApp", engine.newQObject(&app));
    
       auto script =
             "var timer = new QTimer(); \n"
             "timer.interval = 1000; \n"
             "timer.singleShot = true; \n"
             "var conn = timer.timeout.connect(function(){ \n"
             "  print(\"timeout\"); \n"
             "  qApp.quit(); \n"
             "}); \n"
             "timer.start();\n";
    
       engine.evaluate(script);
       return app.exec();
    }
    

提交回复
热议问题