![]() | Home · All Classes · Modules |
The QScriptEngine class provides an environment for evaluating Qt Script code. More...
Inherits QObject.
The QScriptEngine class provides an environment for evaluating Qt Script code.
See the QtScript documentation for information about the Qt Script language, and how to get started with scripting your C++ application.
Use evaluate() to evaluate script code.
QScriptEngine myEngine; QScriptValue three = myEngine.evaluate("1 + 2");
evaluate() can throw a script exception (e.g. due to a syntax error); in that case, the return value is the value that was thrown (typically an Error object). You can check whether the evaluation caused an exception by calling hasUncaughtException(). In that case, you can call toString() on the error object to obtain an error message. The current uncaught exception is also available through uncaughtException(). You can obtain a human-readable backtrace of the exception with uncaughtExceptionBacktrace().
QScriptValue result = myEngine.evaluate(...); if (myEngine.hasUncaughtException()) { int line = myEngine.uncaughtExceptionLineNumber(); qDebug() << "uncaught exception at line" << line << ":" << result.toString(); }
When handling possibly incomplete input, the canEvaluate() function can be used to determine whether code can usefully be passed to evaluate(). This can be useful when implementing tools that allow code to be written incrementally, such as command line interpreters.
Use newObject() to create a standard Qt Script object. You can use the object-specific functionality in QScriptValue to manipulate the script object (e.g. QScriptValue.setProperty()). Use newArray() to create a Qt script array object. Use newDate() to create a Date object, and newRegExp() to create a RegExp object. Use newVariant() to wrap a QVariant.
Use newQObject() to wrap a QObject (or subclass) pointer, and newQMetaObject() to wrap a QMetaObject. When wrapping a QObject pointer with newQObject(), properties, children and signals and slots of the QObject will then become available to script code as properties of the created Qt Script object. No binding code is needed because it is done dynamically using the Qt meta object system. See the QtScript documentation for more information.
Use newFunction() to wrap native (C++) functions, including constructors for your own custom types.
Use importExtension() to import plugin-based extensions into the engine.
Use globalObject() to access the unique Global Object associated with the script engine. Properties of the Global Object are accessible from any script code. Typically, you set properties in the engine's Global Object to make your own extensions available to scripts. Here is an example of how to expose a number value through the Global Object:
QScriptValue myNumber = QScriptValue(&myEngine, 123); myEngine.globalObject().setProperty("myNumber", myNumber); ... QScriptValue myNumberPlusOne = myEngine.evaluate("myNumber + 1");
In addition to exposing plain data, you can also write C++ functions that can be invoked from script code. Such functions must have the signature QScriptEngine.FunctionSignature. You may then pass the function as argument to newFunction(). Here is an example of a function that returns the sum of its first two arguments:
QScriptValue myAdd(QScriptContext *context, QScriptEngine *engine) { QScriptValue a = context->argument(0); QScriptValue b = context->argument(1); return QScriptValue(engine, a.toNumber() + b.toNumber()); }
To expose this function to script code, you can set it as a property of the Global Object:
QScriptValue fun = myEngine.newFunction(myAdd); myEngine.globalObject().setProperty("myAdd", fun);
Once this is done, script code can call your function in the exact same manner as a "normal" script function:
QScriptValue result = myEngine.evaluate("myAdd(myNumber, 1)");
You can define shared script functionality for a custom C++ type by creating your own default prototype object and setting it with setDefaultPrototype(); see also QScriptable.
Use fromScriptValue() to cast from a QScriptValue to another type, and toScriptValue() to create a QScriptValue from another value. You can specify how the conversion of C++ types is to be performed with qScriptRegisterMetaType() and qScriptRegisterSequenceMetaType().
See also QScriptValue and QScriptContext.
These flags specify options when wrapping a QObject pointer with newQObject().
Constant | Value | Description |
---|---|---|
QScriptEngine.ExcludeChildObjects | 0x0001 | The script object will not expose child objects as properties. |
QScriptEngine.ExcludeSuperClassMethods | 0x0002 | The script object will not expose signals and slots inherited from the superclass. |
QScriptEngine.ExcludeSuperClassProperties | 0x0004 | The script object will not expose properties inherited from the superclass. |
QScriptEngine.AutoCreateDynamicProperties | 0x0100 | Properties that don't already exist in the QObject will be created as dynamic properties of that object, rather than as properties of the script object. |
The QObjectWrapOptions type is a typedef for QFlags<QObjectWrapOption>. It stores an OR combination of QObjectWrapOption values.
This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().
Constant | Value | Description |
---|---|---|
QScriptEngine.QtOwnership | 0 | The standard Qt ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in Object Trees and Object Ownership.) |
QScriptEngine.ScriptOwnership | 1 | The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value). |
QScriptEngine.AutoOwnership | 2 | If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership). |
Constructs a QScriptEngine object.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
The parent argument, if not None, causes self to be owned by Qt instead of PyQt.
Constructs a QScriptEngine object with the given parent.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
Returns true if program can be evaluated; i.e. the code is sufficient to determine whether it appears to be a syntactically correct program, or contains a syntax error.
This function returns false if program is incomplete; i.e. the input is syntactically correct up to the point where the input is terminated.
Note that this function only does a static check of program; e.g. it does not check whether references to variables are valid, and so on.
A typical usage of canEvaluate() is to implement an interactive interpreter for QtScript. The user is repeatedly queried for individual lines of code; the lines are concatened internally, and only when canEvaluate() returns true for the resulting program is it passed to evaluate().
The following are some examples to illustrate the behavior of canEvaluate(). (Note that all example inputs are assumed to have an explicit newline as their last character, since otherwise the QtScript parser would automatically insert a semi-colon character at the end of the input, and this could cause canEvaluate() to produce different results.)
Given the input
if (hello && world) print("hello world");
canEvaluate() will return true, since the program appears to be complete.
Given the input
if (hello &&
canEvaluate() will return false, since the if-statement is not complete, but is syntactically correct so far.
Given the input
0 = 0
canEvaluate() will return true, but evaluate() will throw a SyntaxError given the same input.
Given the input
./test.js
canEvaluate() will return true, even though the code is clearly not syntactically valid QtScript code. evaluate() will throw a SyntaxError when this code is evaluated.
Given the input
foo["bar"]
canEvaluate() will return true, but evaluate() will throw a ReferenceError if foo is not defined in the script environment.
See also evaluate().
Runs the garbage collector.
The garbage collector will attempt to reclaim memory by locating and disposing of objects that are no longer reachable in the script environment.
Normally you don't need to call this function; the garbage collector will automatically be invoked when the QScriptEngine decides that it's wise to do so (i.e. when a certain number of new objects have been created). However, you can call this function to explicitly request that garbage collection should be performed as soon as possible.
Returns the current context.
The current context is typically accessed to retrieve the arguments and `this' object in native functions; for convenience, it is available as the first argument in QScriptEngine.FunctionSignature.
Returns the default prototype associated with the given metaTypeId, or an invalid QScriptValue if no default prototype has been set.
See also setDefaultPrototype().
Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation.
The script code will be evaluated in the current context.
The evaluation of program can cause an exception in the engine; in this case the return value will be the exception that was thrown (typically an Error object). You can call hasUncaughtException() to determine if an exception occurred in the last call to evaluate().
lineNumber is used to specify a starting line number for program; line number information reported by the engine that pertain to this evaluation (e.g. uncaughtExceptionLineNumber()) will be based on this argument. For example, if program consists of two lines of code, and the statement on the second line causes a script exception, uncaughtExceptionLineNumber() would return the given lineNumber plus one. When no starting line number is specified, line numbers will be 1-based.
fileName is used for error reporting. For example in error objects the file name is accessible through the "fileName" property if it's provided with this function.
See also canEvaluate() and hasUncaughtException().
Returns this engine's Global Object.
The Global Object contains the built-in objects that are part of ECMA-262, such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code. Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.
Returns true if the last script evaluation (whether direct or indirect) resulted in an uncaught exception; otherwise returns false.
The exception state is cleared every time a script function call is done in the engine, or when evaluate() is called.
See also uncaughtException(), uncaughtExceptionLineNumber(), and uncaughtExceptionBacktrace().
Imports the given extension into this QScriptEngine. Returns undefinedValue() if the extension was successfully imported. You can call hasUncaughtException() to check if an error occurred; in that case, the return value is the value that was thrown by the exception (usually an Error object).
QScriptEngine ensures that a particular extension is only imported once; subsequent calls to importExtension() with the same extension name will do nothing and return undefinedValue().
See also QScriptExtensionPlugin and Creating QtScript Extensions.
Creates a QtScript object of class Array with the given length.
See also newObject().
Creates a QtScript object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC).
This is an overloaded member function, provided for convenience.
Creates a QtScript object of class Date from the given value.
See also QScriptValue.toDateTime().
Creates a QtScript object of class Object.
The prototype of the created object will be the Object prototype object.
See also newArray() and QScriptValue.setProperty().
Creates a QtScript object that represents a QObject class, using the the given metaObject and constructor ctor.
Enums of metaObject are available as properties of the created QScriptValue. When the class is called as a function, ctor will be called to create a new instance of the class.
See also newQObject().
Creates a QtScript object that wraps the given QObject object, using the given ownership. The given options control various aspects of the interaction with the resulting script object.
Signals and slots, properties and children of object are available as properties of the created QScriptValue. For more information, see the QtScript documentation.
If object is a null pointer, this function returns nullValue().
If the given object is deleted outside of QtScript's control, any attempt to access the deleted QObject's members through the QtScript wrapper object (either by script code or C++) will result in a script exception.
See also QScriptValue.toQObject().
Creates a QtScript object of class RegExp with the given regexp.
See also QScriptValue.toRegExp().
This is an overloaded member function, provided for convenience.
Creates a QtScript object of class RegExp with the given pattern and flags.
Creates a QtScript object holding the given variant value.
If a default prototype has been registered with the meta type id of value, then the prototype of the created object will be that prototype; otherwise, the prototype will be the Object prototype object.
See also setDefaultPrototype() and QScriptValue.toVariant().
Returns a QScriptValue of the primitive type Null.
See also undefinedValue().
Returns the interval in milliseconds between calls to QCoreApplication.processEvents() while the interpreter is running.
See also setProcessEventsInterval().
Sets the default prototype of the given metaTypeId to prototype.
The default prototype provides a script interface for values of type metaTypeId when a value of that type is accessed from script code. Whenever the script engine (implicitly or explicitly) creates a QScriptValue from a value of type metaTypeId, the default prototype will be set as the QScriptValue's prototype.
See also defaultPrototype(), qScriptRegisterMetaType(), QScriptable, and Default Prototypes Example.
Sets the interval between calls to QCoreApplication.processEvents to interval milliseconds.
While the interpreter is running, all event processing is by default blocked. This means for instance that the gui will not be updated and timers will not be fired. To allow event processing during interpreter execution one can specify the processing interval to be a positive value, indicating the number of milliseconds between each time QCoreApplication.processEvents() is called.
The default value is -1, which disables event processing during interpreter execution.
See also processEventsInterval().
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception.
The exception value is typically an Error object; in that case, you can call toString() on the return value to obtain an error message.
See also hasUncaughtException(), uncaughtExceptionLineNumber(), and uncaughtExceptionBacktrace().
Returns a human-readable backtrace of the last uncaught exception.
Each line is of the form <function-name>(<arguments>)@<file-name>:<line-number>.
See also uncaughtException().
Returns the line number where the last uncaught exception occurred.
Line numbers are 1-based, unless a different base was specified as the second argument to evaluate().
See also hasUncaughtException() and uncaughtExceptionBacktrace().
Returns a QScriptValue of the primitive type Undefined.
See also nullValue().
PyQt 4.3.1 for X11 | Copyright © Riverbank Computing Ltd and Trolltech AS 2007 | Qt 4.3.0 |