javascript - 匿名 qt 脚本函数的上下文?

标签 javascript qt qtscript

我想从 C++ 执行一个匿名的 Qt 脚本函数,但不知道要使用的 QScriptContext。

这是脚本:

{
  otherObject.Text = "Hello World";
  setTimeout(function(otherObject) { otherObject.Text = "Goodbye World"; }, 9000 );
}

这是 c++ 中的 setTimeout 方法:

QScriptValue setTimeout( QScriptContext* ctx, QScriptEngine* eng )
{
  // How can I obtain the correct context and arg list for the anonymous function here?
}

QScriptValue 对象的调用方法需要上下文和参数列表:

call( ctx->thisObject(), ctx->argumentsObject() );

编辑:上下文可以是全局上下文,但构建参数列表以调用函数似乎是问题的症结所在。我没有看到任何解释如何从 C++ 构建“参数对象”的内容。有一个叫“arguments”的属性,但是好像没有填写,或者我还没想好怎么用。

最佳答案

如果我们只看这段 javascript 代码:

{
    otherObject.Text = "Hello World";
    setTimeout(function(otherObject) { otherObject.Text = "Goodbye World"; }, 9000 );
}

setTimeout 被告知等待 9000,然后调用匿名函数。但是,问题是匿名函数有一个参数。并且setTimeout函数不知道传递给函数什么参数。

<html>
<script>
var otherObject = 'Hello World';
setTimeout(function(otherObject){alert(otherObject);}, 1000);
</script>
</html>

如果你在 chrome 中尝试这段代码,它会提示未定义,因为 setTimeout 函数不知道要传递给匿名函数什么,它只是不传递任何参数。

但是如果你尝试这样做:

<html>
<script>
var otherObject = 'Hello World';
setTimeout(function(){alert(otherObject);}, 1000);
</script>
</html>

它会提示Hello world,因为现在otherObject不再是匿名函数的参数,而是一个与匿名函数形成闭包的局部变量。

因此,为了使您的代码正常工作,setTimeout 函数应该与浏览器的 setTimeout 函数不同。如果你想从 C++ 端为匿名函数设置参数,你可以这样做:

QScriptValue setTimeout( QScriptContext* ctx, QScriptEngine* eng )
{
    QScriptValue anonymous_callback = ctx->argument(0);
    QScriptValue time = ctx->argument(1);
    QThread::sleep(time.toInt32())
    // Then Invoke the anonymous function:
    QScriptValueList args;
    otherObjectProto * otherObjectQtSide = new otherObjectProto();
    otherObjectQtSide.setProperty("Text","Goodbye World!");
    QScriptValue otherObject = engine->newQObject(otherObjectQtSide);// engine is pointer to the QScriptEngine instance
    args << otherObject;
    anonymous_callback.call(QScriptValue(),args);
}

为简单起见,我没有包括三件事:

  1. otherObjectProto 未实现。看here举个例子。

  2. QThread::sleep 正在阻塞当前线程,这可能不是我们想要的,但可以使用 QTimer 轻松地将其修改为异步。

  3. engine->newQObject还有其他参数,定义了QObject的所有权,如果不想内存泄漏,最好看一下。

关于javascript - 匿名 qt 脚本函数的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752401/

相关文章:

javascript - 选择AngularJS中的所有复选框

c++ - 将 QRegularExpression 应用于句子时避免\r

c++ - 如何将类方法转换为 QScriptEngine::FunctionSignature

c++ - 对类型 'const QVariant' 的引用无法绑定(bind)到类型 'void' 的右值

Qt:Q_PROPERTY 带有指针和用于 QtScript 访问的前向声明

c++ - 设计接受从 QtScript 传递的可变数量参数的 C++ 方法

javascript - 实时 webRTC 音频波形

javascript - 检索内联元素相对于父文本行的位置和尺寸

javascript - 分析 Typescript 文件以获取类结构

c++ - 继承类的复制构造函数