0

有没有关于插槽或从脚本访问 c++ 值的好的 QtScript 教程?我需要的只是外部文件中的一个函数,它在数组值上使用一些正则表达式,然后将输出发送回主程序。

我知道,它可以使用信号/插槽来完成,但它看起来像开销,我相信有更简单的方法。

4

2 回答 2

3

听起来您想要做的是在定义函数的文件上使用QScriptEngine::evaluate()(作为脚本文本传入),然后使用QScriptEngine::call()调用它。不需要信号或插槽。

这些方面的东西(未经测试):

QScriptEngine engine;

// Use evaluate to get a QScriptValue that holds the function
QScriptValue functionSV = engine.evaluate(
    "function cube(x) { return x * x * x; }"
);

// Build an argument list of QScriptValue types to proxy the C++
// types into a format that the script engine can understand
QScriptValueList argsSV;
argsSV << 3;

// Make an empty script value for "this" object when we invoke
// cube(), since it's a global function
QScriptValue thisSV ();

// Call the function, getting back a ScriptValue
QScriptValue resultSV = functionSV.call(thisSV, argsSV);

if (engine.hasUncaughtException() || !resultSV.isNumber()) {
    // The code had an uncaught exception or didn't return
    // the type you were expecting.

    // (...error handling...)

} else {
    // Convert the result to a C++ type
    int result = resultSv.toInt();

    // (...do whatever you want to do w/the result...)
}

请注意,您必须进行很多来回转换。如果你只想要 Qt 中的正则表达式,它们已经存在:QRegExp. 示例中包含一个演示:

http://doc.trolltech.com/4.2/tools-regexp.html

于 2010-01-08T01:56:27.420 回答
0

令人惊讶的是,像脚本这样一个中等复杂的问题竟然被专家们弄得一团糟,以至于没有人理解他们想要做什么。所有成功的教学规则都被违反了,从引导这里的用户的问题来看,结果是一场灾难。

脚本是一种表示特定通信的符号形式,在这种情况下,是要执行的操作。该过程需要设计翻译词典,请注意,这永远不会完成,只会发生魔术,将脚本翻译成预定义的结果。然而,脚本引擎的任务总是在它有任何信息之前评估脚本。这显示了白痴的教学。

在您展示脚本引擎评估任何脚本之前,必须向学生展示如何教引擎执行评估。在我回顾的十五个脚本示例中,从来没有这样做过。因此,Qt Script 必须按照您的定义执行魔法。除了心灵感应之外,没有其他可能。你把自己置身于一个讨厌的盒子里,所以我希望你知道现在会发生什么。

于 2014-02-14T02:38:04.627 回答