tags:

views:

198

answers:

1

Hello everyone. Is there any good QtScript tutorial that isn't about slots or accessing c++ values from script? All I need is one function in external file that uses some regexps on array values and then sends output back to main programm.

I understand, that it can be done using signals/slots, but it looks like overhead and I'm sure there's simplier way.

A: 

It sounds like what you want to do is to use QScriptEngine::evaluate() on that file defining the function (passed in as script text) and then invoke it with QScriptEngine::call(). No signals or slots necessary.

Something along these lines (untested):

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...)
}

Note that there's a lot of converting back and forth you'll have to do. If you just want regular expressions in Qt, they already exist: QRegExp. There's a demo included in the samples:

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

Hostile Fork