在qtScript上JavaScript的setTimeout相当于什么? [英] What is the equivalent of JavaScript's setTimeout on qtScript?

查看:170
本文介绍了在qtScript上JavaScript的setTimeout相当于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加量不大;在qtScript上JavaScript的setTimeout相当于什么?

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

推荐答案

以下是通过提供自包含来扩展脚本语言的方法C ++方法(不需要记录定时器ID等)。只需创建名为setTimeout的以下插槽:

Here's how you can extend your script language, by providing a self-contained C++ method (no need for bookkeeping of timer ids or so). Just create the following slot called "setTimeout":

void ScriptGlobalObject::setTimeout(QScriptValue fn, int milliseconds)
{
  if (fn.isFunction())
  {
    QTimer *timer = new QTimer(0);
    qScriptConnect(timer, SIGNAL(timeout()), QScriptValue(), fn);
    connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
    timer->setSingleShot(true);
    timer->start(milliseconds);
  } else
    context()->throwError(tr("Passed parameter '%1' is not a function.").arg(fn.toString()));
}

并将该插槽作为函数引入脚本引擎的全局对象。这可以以不同的方式完成,例如,只需通过QScriptEngine实例创建一个QScriptValue函数,并在引擎的现有全局对象上设置相应的命名属性。但是,在我的情况下,整个ScriptGlobalObject实例被设置为新的全局对象,如下所示:

And introduce that slot as function to the global object of your script engine. This can be done in different ways, e.g. just creating a QScriptValue-function via the QScriptEngine instance, and setting an accordingly named property on the engine's existing global object. In my case however, the entire ScriptGlobalObject instance is set as new global object, like this:

mScriptGlobalObject = new ScriptGlobalObject(this);
engine->setGlobalObject(engine->newQObject(mScriptGlobalObject));

注意,如果你想使用上面的setTimeout代码中显示的context(),你的ScriptGlobalObject也应该来自QScriptable,如下所示:

Note that if you want to use "context()" as shown in the setTimeout code above, your ScriptGlobalObject should derive also from QScriptable, like this:

class ScriptGlobalObject : public QObject, protected QScriptable






在脚本中,您现在可以使用setTimeout来调用稍后调用的方法(只要它起源的QScriptEngine实例在此期间不被删除):


In the script you can now use setTimeout to have a method invoked at a later time (as long as the QScriptEngine instance from which it originates isn't deleted in the meantime):

setTimeout(function() {
  // do something in three seconds
}, 3000);

这篇关于在qtScript上JavaScript的setTimeout相当于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆