Qt 4.8
|
The QScriptEngine class provides an environment for evaluating Qt Script code. More...
#include <qscriptengine.h>
Public Types | |
typedef void(* | DemarshalFunction) (const QScriptValue &, void *) |
typedef QScriptValue(* | FunctionSignature) (QScriptContext *, QScriptEngine *) |
typedef QScriptValue(* | FunctionWithArgSignature) (QScriptContext *, QScriptEngine *, void *) |
typedef QScriptValue(* | MarshalFunction) (QScriptEngine *, const void *) |
enum | QObjectWrapOption { ExcludeChildObjects = 0x0001, ExcludeSuperClassMethods = 0x0002, ExcludeSuperClassProperties = 0x0004, ExcludeSuperClassContents = 0x0006, SkipMethodsInEnumeration = 0x0008, ExcludeDeleteLater = 0x0010, ExcludeSlots = 0x0020, AutoCreateDynamicProperties = 0x0100, PreferExistingWrapperObject = 0x0200 } |
These flags specify options when wrapping a QObject pointer with newQObject(). More... | |
enum | ValueOwnership { QtOwnership, ScriptOwnership, AutoOwnership } |
This enum specifies the ownership when wrapping a C++ value, e. More... | |
Signals | |
void | signalHandlerException (const QScriptValue &exception) |
This signal is emitted when a script function connected to a signal causes an exception. More... | |
Signals inherited from QObject | |
void | destroyed (QObject *=0) |
This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More... | |
Public Functions | |
void | abortEvaluation (const QScriptValue &result=QScriptValue()) |
Aborts any script evaluation currently taking place in this engine. More... | |
QScriptEngineAgent * | agent () const |
Returns the agent currently installed on this engine, or 0 if no agent is installed. More... | |
QStringList | availableExtensions () const |
Returns a list naming the available extensions that can be imported using the importExtension() function. More... | |
bool | canEvaluate (const QString &program) const |
Returns true if program can be evaluated; i. More... | |
void | clearExceptions () |
Clears any uncaught exceptions in this engine. More... | |
void | collectGarbage () |
Runs the garbage collector. More... | |
QScriptContext * | currentContext () const |
Returns the current context. More... | |
QScriptValue | defaultPrototype (int metaTypeId) const |
Returns the default prototype associated with the given metaTypeId, or an invalid QScriptValue if no default prototype has been set. More... | |
QScriptValue | evaluate (const QString &program, const QString &fileName=QString(), int lineNumber=1) |
Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation. More... | |
QScriptValue | evaluate (const QScriptProgram &program) |
Evaluates the given program and returns the result of the evaluation. More... | |
template<typename T > | |
T | fromScriptValue (const QScriptValue &value) |
Returns the given value converted to the template type T . More... | |
QScriptValue | globalObject () const |
Returns this engine's Global Object. More... | |
bool | hasUncaughtException () const |
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false. More... | |
QStringList | importedExtensions () const |
Returns a list naming the extensions that have been imported using the importExtension() function. More... | |
QScriptValue | importExtension (const QString &extension) |
Imports the given extension into this QScriptEngine. More... | |
void | installTranslatorFunctions (const QScriptValue &object=QScriptValue()) |
Installs translator functions on the given object, or on the Global Object if no object is specified. More... | |
bool | isEvaluating () const |
Returns true if this engine is currently evaluating a script, otherwise returns false. More... | |
QScriptValue | newActivationObject () |
QScriptValue | newArray (uint length=0) |
Creates a QtScript object of class Array with the given length. More... | |
QScriptValue | newDate (qsreal value) |
Creates a QtScript object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC). More... | |
QScriptValue | newDate (const QDateTime &value) |
Creates a QtScript object of class Date from the given value. More... | |
QScriptValue | newFunction (FunctionSignature signature, int length=0) |
Creates a QScriptValue that wraps a native (C++) function. More... | |
QScriptValue | newFunction (FunctionSignature signature, const QScriptValue &prototype, int length=0) |
Creates a constructor function from fun, with the given length. More... | |
QScriptValue | newFunction (FunctionWithArgSignature signature, void *arg) |
QScriptValue | newObject () |
Creates a QtScript object of class Object. More... | |
QScriptValue | newObject (QScriptClass *scriptClass, const QScriptValue &data=QScriptValue()) |
Creates a QtScript Object of the given class, scriptClass. More... | |
QScriptValue | newQMetaObject (const QMetaObject *metaObject, const QScriptValue &ctor=QScriptValue()) |
Creates a QtScript object that represents a QObject class, using the the given metaObject and constructor ctor. More... | |
QScriptValue | newQObject (QObject *object, ValueOwnership ownership=QtOwnership, const QObjectWrapOptions &options=0) |
Creates a QtScript object that wraps the given QObject object, using the given ownership. More... | |
QScriptValue | newQObject (const QScriptValue &scriptObject, QObject *qtObject, ValueOwnership ownership=QtOwnership, const QObjectWrapOptions &options=0) |
Initializes the given scriptObject to hold the given qtObject, and returns the scriptObject. More... | |
QScriptValue | newRegExp (const QRegExp ®exp) |
Creates a QtScript object of class RegExp with the given regexp. More... | |
QScriptValue | newRegExp (const QString &pattern, const QString &flags) |
Creates a QtScript object of class RegExp with the given pattern and flags. More... | |
QScriptValue | newVariant (const QVariant &value) |
Creates a QtScript object holding the given variant value. More... | |
QScriptValue | newVariant (const QScriptValue &object, const QVariant &value) |
Initializes the given Qt Script object to hold the given variant value, and returns the object. More... | |
QScriptValue | nullValue () |
Returns a QScriptValue of the primitive type Null. More... | |
QScriptValue | objectById (qint64 id) const |
Returns the object with the given id, or an invalid QScriptValue if there is no object with that id. More... | |
void | popContext () |
Pops the current execution context and restores the previous one. More... | |
int | processEventsInterval () const |
Returns the interval in milliseconds between calls to QCoreApplication::processEvents() while the interpreter is running. More... | |
QScriptContext * | pushContext () |
Enters a new execution context and returns the associated QScriptContext object. More... | |
QScriptEngine () | |
Constructs a QScriptEngine object. More... | |
QScriptEngine (QObject *parent) | |
Constructs a QScriptEngine object with the given parent. More... | |
void | reportAdditionalMemoryCost (int size) |
Reports an additional memory cost of the given size, measured in bytes, to the garbage collector. More... | |
template<class T > | |
QScriptValue | scriptValueFromQMetaObject () |
Creates a QScriptValue that represents the Qt class T . More... | |
void | setAgent (QScriptEngineAgent *agent) |
Installs the given agent on this engine. More... | |
void | setDefaultPrototype (int metaTypeId, const QScriptValue &prototype) |
Sets the default prototype of the C++ type identified by the given metaTypeId to prototype. More... | |
void | setGlobalObject (const QScriptValue &object) |
Sets this engine's Global Object to be the given object. More... | |
void | setProcessEventsInterval (int interval) |
Sets the interval between calls to QCoreApplication::processEvents to interval milliseconds. More... | |
QScriptValue | toObject (const QScriptValue &value) |
Converts the given value to an object, if such a conversion is possible; otherwise returns an invalid QScriptValue. More... | |
template<typename T > | |
QScriptValue | toScriptValue (const T &value) |
Creates a QScriptValue with the given value. More... | |
QScriptString | toStringHandle (const QString &str) |
Returns a handle that represents the given string, str. More... | |
QScriptValue | uncaughtException () const |
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception. More... | |
QStringList | uncaughtExceptionBacktrace () const |
Returns a human-readable backtrace of the last uncaught exception. More... | |
int | uncaughtExceptionLineNumber () const |
Returns the line number where the last uncaught exception occurred. More... | |
QScriptValue | undefinedValue () |
Returns a QScriptValue of the primitive type Undefined. More... | |
virtual | ~QScriptEngine () |
Destroys this QScriptEngine. More... | |
Public Functions inherited from QObject | |
bool | blockSignals (bool b) |
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More... | |
const QObjectList & | children () const |
Returns a list of child objects. More... | |
bool | connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const |
bool | disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0) |
bool | disconnect (const QObject *receiver, const char *member=0) |
void | dumpObjectInfo () |
Dumps information about signal connections, etc. More... | |
void | dumpObjectTree () |
Dumps a tree of children to the debug output. More... | |
QList< QByteArray > | dynamicPropertyNames () const |
Returns the names of all properties that were dynamically added to the object using setProperty(). More... | |
virtual bool | event (QEvent *) |
This virtual function receives events to an object and should return true if the event e was recognized and processed. More... | |
virtual bool | eventFilter (QObject *, QEvent *) |
Filters events if this object has been installed as an event filter for the watched object. More... | |
template<typename T > | |
T | findChild (const QString &aName=QString()) const |
Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More... | |
template<typename T > | |
QList< T > | findChildren (const QString &aName=QString()) const |
Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More... | |
template<typename T > | |
QList< T > | findChildren (const QRegExp &re) const |
bool | inherits (const char *classname) const |
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More... | |
void | installEventFilter (QObject *) |
Installs an event filter filterObj on this object. More... | |
bool | isWidgetType () const |
Returns true if the object is a widget; otherwise returns false. More... | |
void | killTimer (int id) |
Kills the timer with timer identifier, id. More... | |
virtual const QMetaObject * | metaObject () const |
Returns a pointer to the meta-object of this object. More... | |
void | moveToThread (QThread *thread) |
Changes the thread affinity for this object and its children. More... | |
QString | objectName () const |
QObject * | parent () const |
Returns a pointer to the parent object. More... | |
QVariant | property (const char *name) const |
Returns the value of the object's name property. More... | |
Q_INVOKABLE | QObject (QObject *parent=0) |
Constructs an object with parent object parent. More... | |
void | removeEventFilter (QObject *) |
Removes an event filter object obj from this object. More... | |
void | setObjectName (const QString &name) |
void | setParent (QObject *) |
Makes the object a child of parent. More... | |
bool | setProperty (const char *name, const QVariant &value) |
Sets the value of the object's name property to value. More... | |
void | setUserData (uint id, QObjectUserData *data) |
bool | signalsBlocked () const |
Returns true if signals are blocked; otherwise returns false. More... | |
int | startTimer (int interval) |
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More... | |
QThread * | thread () const |
Returns the thread in which the object lives. More... | |
QObjectUserData * | userData (uint id) const |
virtual | ~QObject () |
Destroys the object, deleting all its child objects. More... | |
Static Public Functions | |
static QScriptSyntaxCheckResult | checkSyntax (const QString &program) |
Checks the syntax of the given program. More... | |
Static Public Functions inherited from QObject | |
static bool | connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection) |
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More... | |
static bool | connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection) |
static bool | disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member) |
Disconnects signal in object sender from method in object receiver. More... | |
static bool | disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member) |
static uint | registerUserData () |
static QString | tr (const char *sourceText, const char *comment=0, int n=-1) |
static QString | trUtf8 (const char *sourceText, const char *comment=0, int n=-1) |
Protected Functions | |
QScriptEngine (QScriptEnginePrivate &dd, QObject *parent=0) | |
Protected Functions inherited from QObject | |
virtual void | childEvent (QChildEvent *) |
This event handler can be reimplemented in a subclass to receive child events. More... | |
virtual void | connectNotify (const char *signal) |
This virtual function is called when something has been connected to signal in this object. More... | |
virtual void | customEvent (QEvent *) |
This event handler can be reimplemented in a subclass to receive custom events. More... | |
virtual void | disconnectNotify (const char *signal) |
This virtual function is called when something has been disconnected from signal in this object. More... | |
QObject (QObjectPrivate &dd, QObject *parent=0) | |
int | receivers (const char *signal) const |
Returns the number of receivers connected to the signal. More... | |
QObject * | sender () const |
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More... | |
int | senderSignalIndex () const |
virtual void | timerEvent (QTimerEvent *) |
This event handler can be reimplemented in a subclass to receive timer events for the object. More... | |
Private Functions | |
bool | convert (const QScriptValue &value, int type, void *ptr) |
QScriptValue | create (int type, const void *ptr) |
void | registerCustomType (int type, MarshalFunction mf, DemarshalFunction df, const QScriptValue &prototype) |
Static Private Functions | |
static bool | convertV2 (const QScriptValue &value, int type, void *ptr) |
Friends | |
void | qScriptRegisterMetaType_helper (QScriptEngine *, int, MarshalFunction, DemarshalFunction, const QScriptValue &) |
bool | qscriptvalue_cast_helper (const QScriptValue &, int, void *) |
QScriptValue | qScriptValueFromValue_helper (QScriptEngine *, int, const void *) |
Related Functions | |
(Note that these are not member functions.) | |
FunctionSignature | |
FunctionWithArgSignature | |
bool | qScriptConnect (QObject *sender, const char *signal, const QScriptValue &receiver, const QScriptValue &function) |
Creates a connection from the signal in the sender to the given function. More... | |
bool | qScriptDisconnect (QObject *sender, const char *signal, const QScriptValue &receiver, const QScriptValue &function) |
Disconnects the signal in the sender from the given (receiver, function) pair. More... | |
int | qScriptRegisterMetaType (QScriptEngine *engine, QScriptValue(*toScriptValue)(QScriptEngine *, const T &t), void(*fromScriptValue)(const QScriptValue &, T &t), const QScriptValue &prototype=QScriptValue()) |
int | qScriptRegisterSequenceMetaType (QScriptEngine *engine, const QScriptValue &prototype=QScriptValue()) |
QScriptValue | qScriptValueFromQMetaObject (QScriptEngine *engine) |
QScriptValue | qScriptValueFromSequence (QScriptEngine *engine, const Container &container) |
QScriptValue | qScriptValueFromValue (QScriptEngine *engine, const T &value) |
void | qScriptValueToSequence (const QScriptValue &value, Container &container) |
Copies the elements in the sequence specified by value to the given container of template type Container . More... | |
T | qScriptValueToValue (const QScriptValue &value) |
Returns the given value converted to the template type T . More... | |
Related Functions inherited from QObject | |
T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QRegExp ®Exp)() |
T * | qobject_cast (QObject *object) |
QObjectList | |
void * | qt_find_obj_child (QObject *parent, const char *type, const QString &name) |
Returns a pointer to the object named name that inherits type and with a given parent. More... | |
Additional Inherited Members | |
Public Slots inherited from QObject | |
void | deleteLater () |
Schedules this object for deletion. More... | |
Static Public Variables inherited from QObject | |
static const QMetaObject | staticMetaObject |
This variable stores the meta-object for the class. More... | |
Protected Variables inherited from QObject | |
QScopedPointer< QObjectData > | d_ptr |
Static Protected Variables inherited from QObject | |
static const QMetaObject | staticQtMetaObject |
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; this is the C++ equivalent of the built-in script function eval()
.
evaluate() returns a QScriptValue that holds the result of the evaluation. The QScriptValue class provides functions for converting the result to various C++ types (e.g. QScriptValue::toString() and QScriptValue::toNumber()).
The following code snippet shows how a script function can be defined and then invoked from C++ using QScriptValue::call():
As can be seen from the above snippets, a script is provided to the engine in the form of a string. One common way of loading scripts is by reading the contents of a file and passing it to evaluate():
Here we pass the name of the file as the second argument to evaluate(). This does not affect evaluation in any way; the second argument is a general-purpose string that is used to identify the script for debugging purposes (for example, our filename will now show up in any uncaughtExceptionBacktrace() involving the script).
The globalObject() function returns the Global Object associated with the script engine. Properties of the Global Object are accessible from any script code (i.e. they are global variables). Typically, before evaluating "user" scripts, you will want to configure a script engine by adding one or more properties to the Global Object:
Adding custom properties to the scripting environment is one of the standard means of providing a scripting API that is specific to your application. Usually these custom properties are objects created by the newQObject() or newObject() functions, or constructor functions created by newFunction().
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(). Calling clearExceptions() will cause any uncaught exceptions to be cleared.
The checkSyntax() function can be used to determine whether code can be usefully passed to evaluate().
Use newObject() to create a standard Qt Script object; this is the C++ equivalent of the script statement new Object()
. You can use the object-specific functionality in QScriptValue to manipulate the script object (e.g. QScriptValue::setProperty()). Similarly, use newArray() to create a Qt Script array object. Use newDate() to create a Date
object, and newRegExp() to create a RegExp
object.
Use newQObject() to wrap a QObject (or subclass) pointer. newQObject() returns a proxy script object; properties, children, and signals and slots of the QObject are available as properties of the proxy object. No binding code is needed because it is done dynamically using the Qt meta object system.
Use qScriptConnect() to connect a C++ signal to a script function; this is the Qt Script equivalent of QObject::connect(). When a script function is invoked in response to a C++ signal, it can cause a script exception; you can connect to the signalHandlerException() signal to catch such an exception.
Use newQMetaObject() to wrap a QMetaObject; this gives you a "script representation" of a QObject-based class. newQMetaObject() returns a proxy script object; enum values of the class are available as properties of the proxy object. You can also specify a function that will be used to construct objects of the class (e.g. when the constructor is invoked from a script). For classes that have a "standard" Qt constructor, Qt Script can provide a default script constructor for you; see scriptValueFromQMetaObject().
For more information about QObject integration, see Making Applications Scriptable
Use newVariant() to wrap a QVariant. This can be used to store values of custom (non-QObject) C++ types that have been registered with the Qt meta-type system. To make such types scriptable, you typically associate a prototype (delegate) object with the C++ type by calling setDefaultPrototype(); the prototype object defines the scripting API for the C++ type. Unlike the QObject integration, there is no automatic binding possible here; i.e. you have to create the scripting API yourself, for example by using the QScriptable class.
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(). By default, Qt Script will use QVariant to store values of custom types.
Use importExtension() to import plugin-based extensions into the engine. Call availableExtensions() to obtain a list naming all the available extensions, and importedExtensions() to obtain a list naming only those extensions that have been imported.
Call pushContext() to open up a new variable scope, and popContext() to close the current scope. This is useful if you are implementing an extension that evaluates script code containing temporary variable definitions (e.g. var foo = 123;
) that are safe to discard when evaluation has completed.
Use newFunction() to wrap native (C++) functions, including constructors for your own custom types, so that these 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:
To expose this function to script code, you can set it as a property of the Global Object:
Once this is done, script code can call your function in the exact same manner as a "normal" script function:
If you need to evaluate possibly long-running scripts from the main (GUI) thread, you should first call setProcessEventsInterval() to make sure that the GUI stays responsive. You can abort a currently running script by calling abortEvaluation(). You can determine whether an engine is currently running a script by calling isEvaluating().
Qt Script objects may be garbage collected when they are no longer referenced. There is no guarantee as to when automatic garbage collection will take place.
The collectGarbage() function can be called to explicitly request garbage collection.
The reportAdditionalMemoryCost() function can be called to indicate that a Qt Script object occupies memory that isn't managed by the scripting environment. Reporting the additional cost makes it more likely that the garbage collector will be triggered. This can be useful, for example, when many custom, native Qt Script objects are allocated.
Since Qt 4.4, you can be notified of events pertaining to script execution (e.g. script function calls and statement execution) through the QScriptEngineAgent interface; see the setAgent() function. This can be used to implement debugging and profiling of a QScriptEngine.
Definition at line 104 of file qscriptengine.h.
QScriptEngine::DemarshalFunction |
Definition at line 208 of file qscriptengine.h.
typedef QScriptValue(* QScriptEngine::FunctionSignature) (QScriptContext *, QScriptEngine *) |
Definition at line 165 of file qscriptengine.h.
typedef QScriptValue(* QScriptEngine::FunctionWithArgSignature) (QScriptContext *, QScriptEngine *, void *) |
Definition at line 166 of file qscriptengine.h.
QScriptEngine::MarshalFunction |
Definition at line 207 of file qscriptengine.h.
These flags specify options when wrapping a QObject pointer with newQObject().
Definition at line 119 of file qscriptengine.h.
This enum specifies the ownership when wrapping a C++ value, e.
g. by using newQObject().
\arg \b QtOwnership 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 <b>Object Trees & Ownership</b>.) \arg \b ScriptOwnership 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). \arg \b AutoOwnership If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership).
Enumerator | |
---|---|
QtOwnership | |
ScriptOwnership | |
AutoOwnership |
Definition at line 113 of file qscriptengine.h.
QScriptEngine::QScriptEngine | ( | ) |
Constructs a QScriptEngine object.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
Definition at line 1984 of file qscriptengine.cpp.
Referenced by QScriptEnginePrivate::toStringHandle().
|
explicit |
Constructs a QScriptEngine object with the given parent.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
Definition at line 1996 of file qscriptengine.cpp.
|
virtual |
|
protected |
Definition at line 2003 of file qscriptengine.cpp.
void QScriptEngine::abortEvaluation | ( | const QScriptValue & | result = QScriptValue() | ) |
Aborts any script evaluation currently taking place in this engine.
The given result is passed back as the result of the evaluation (i.e. it is returned from the call to evaluate() being aborted).
If the engine isn't evaluating a script (i.e. isEvaluating() returns false), this function does nothing.
Call this function if you need to abort a running script for some reason, e.g. when you have detected that the script has been running for several seconds without completing.
Definition at line 4216 of file qscriptengine.cpp.
QScriptEngineAgent * QScriptEngine::agent | ( | ) | const |
Returns the agent currently installed on this engine, or 0 if no agent is installed.
Definition at line 4353 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::detach(), popContext(), QScriptDeclarativeClass::pushCleanContext(), pushContext(), and setAgent().
QStringList QScriptEngine::availableExtensions | ( | ) | const |
Returns a list naming the available extensions that can be imported using the importExtension() function.
This list includes extensions that have been imported.
Definition at line 3754 of file qscriptengine.cpp.
bool QScriptEngine::canEvaluate | ( | const QString & | program | ) | const |
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
canEvaluate() will return true, since the program appears to be complete.
Given the input
canEvaluate() will return false, since the if-statement is not complete, but is syntactically correct so far.
Given the input
canEvaluate() will return true, but evaluate() will throw a SyntaxError given the same input.
Given the input
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
canEvaluate() will return true, but evaluate() will throw a ReferenceError if foo
is not defined in the script environment.
Definition at line 2592 of file qscriptengine.cpp.
|
static |
Checks the syntax of the given program.
Returns a QScriptSyntaxCheckResult object that contains the result of the check.
Definition at line 2614 of file qscriptengine.cpp.
Referenced by QScriptDebuggerConsoleGlobalObject::checkSyntax(), QScriptDebuggerConsole::consumeInput(), QScriptDebuggerLocalsItemDelegate::eventFilter(), QScriptBreakpointsItemDelegate::eventFilter(), QScriptDebuggerLocalsItemDelegate::setModelData(), QScriptBreakpointsItemDelegate::setModelData(), QScriptDebuggerLocalsItemDelegate::validateInput(), and QScriptBreakpointsItemDelegate::validateInput().
void QScriptEngine::clearExceptions | ( | ) |
Clears any uncaught exceptions in this engine.
Definition at line 2970 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::doPendingEvaluate(), QDeclarativeQtScriptExpression::eval(), QScriptDebuggerCommandExecutor::execute(), QDeclarativeInclude::finished(), QScriptDebuggerAgent::functionExit(), QDeclarativeInclude::include(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QDeclarativeWorkerScriptEnginePrivate::processMessage(), and QDeclarativeInclude::worker_include().
void QScriptEngine::collectGarbage | ( | ) |
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.
Definition at line 4097 of file qscriptengine.cpp.
|
private |
Definition at line 3461 of file qscriptengine.cpp.
|
staticprivate |
Definition at line 3471 of file qscriptengine.cpp.
Referenced by qscriptvalue_cast_helper().
|
private |
Definition at line 3049 of file qscriptengine.cpp.
Referenced by QScriptEnginePrivate::create(), and qScriptValueFromValue_helper().
QScriptContext * QScriptEngine::currentContext | ( | ) | const |
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.
Definition at line 2720 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::backtrace(), QScriptDebuggerBackend::context(), QDeclarativeObjectScriptClass::destroy(), QScriptDebuggerAgent::enterReturnByForceMode(), importExtension(), QJSDebuggerAgent::localsAtFrame(), popContext(), QJSDebuggerAgentPrivate::positionChange(), QScriptDebuggerAgent::QScriptDebuggerAgent(), and QDeclarativeGlobalScriptClass::setProperty().
QScriptValue QScriptEngine::defaultPrototype | ( | int | metaTypeId | ) | const |
Returns the default prototype associated with the given metaTypeId, or an invalid QScriptValue if no default prototype has been set.
Definition at line 2984 of file qscriptengine.cpp.
QScriptValue QScriptEngine::evaluate | ( | const QString & | program, |
const QString & | fileName = QString() , |
||
int | lineNumber = 1 |
||
) |
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.
Definition at line 2671 of file qscriptengine.cpp.
Referenced by QDeclarativeContextData::addImportedScript(), QScriptDebuggerBackend::doPendingEvaluate(), QDeclarativeExpressionPrivate::evalInObjectScope(), QDeclarativeInclude::finished(), importExtension(), QDeclarativeInclude::include(), QDeclarativeExpressionPrivate::init(), QScriptDebuggerScriptedConsoleCommand::parse(), QScriptDebuggerAgent::positionChange(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QDeclarativeExpressionPrivate::scriptValue(), QJSDebuggerAgent::setProperty(), and QDeclarativeInclude::worker_include().
QScriptValue QScriptEngine::evaluate | ( | const QScriptProgram & | program | ) |
Evaluates the given program and returns the result of the evaluation.
Definition at line 2695 of file qscriptengine.cpp.
|
inline |
Returns the given value converted to the template type T
.
Note that T
must be known to QMetaType.
See Conversion Between QtScript and C++ Types for a description of the built-in type conversion provided by QtScript.
Definition at line 218 of file qscriptengine.h.
QScriptValue QScriptEngine::globalObject | ( | ) | const |
Returns this engine's Global Object.
By default, 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.
Definition at line 2030 of file qscriptengine.cpp.
Referenced by QScript::__setupPackage__(), QScriptContext::activationObject(), QScriptDebuggerBackend::attachTo(), QScriptDebuggerBackend::detach(), QDeclarativeGlobalScriptClass::explicitSetProperty(), QJSDebuggerAgentPrivate::getLocals(), importExtension(), QtDBusScriptPlugin::initialize(), QScriptDebuggerScriptedConsoleCommand::parse(), QDBusConnectionConstructor::QDBusConnectionConstructor(), QDeclarativeGlobalScriptClass::QDeclarativeGlobalScriptClass(), QDeclarativeScriptEngine::QDeclarativeScriptEngine(), qt_add_qmlsqldatabase(), qt_add_qmlxmlhttprequest(), QScriptExtensionPlugin::setupPackage(), and QScriptDebuggerScriptedConsoleCommandJob::start().
bool QScriptEngine::hasUncaughtException | ( | ) | const |
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false.
The exception state is cleared when evaluate() is called.
Definition at line 2893 of file qscriptengine.cpp.
Referenced by QDeclarativeContextData::addImportedScript(), QScriptDebuggerBackend::doPendingEvaluate(), QDeclarativeQtScriptExpression::eval(), QDeclarativeExpressionPrivate::exceptionToError(), QScriptDebuggerCommandExecutor::execute(), QDeclarativeInclude::finished(), importExtension(), QDeclarativeInclude::include(), QScriptDebuggerScriptedConsoleCommand::parse(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QDeclarativeWorkerScriptEnginePrivate::processMessage(), qmlsqldatabase_change_version(), qmlsqldatabase_transaction_shared(), QDeclarativeWorkerScriptEnginePrivate::reportScriptException(), uncaughtExceptionBacktrace(), uncaughtExceptionLineNumber(), and QDeclarativeInclude::worker_include().
QStringList QScriptEngine::importedExtensions | ( | ) | const |
Returns a list naming the extensions that have been imported using the importExtension() function.
Definition at line 3831 of file qscriptengine.cpp.
QScriptValue QScriptEngine::importExtension | ( | const QString & | extension | ) |
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().
Definition at line 3572 of file qscriptengine.cpp.
void QScriptEngine::installTranslatorFunctions | ( | const QScriptValue & | object = QScriptValue() | ) |
Installs translator functions on the given object, or on the Global Object if no object is specified.
The relation between Qt Script translator functions and C++ translator functions is described in the following table:
Script Function | Corresponding C++ Function |
qsTr() | QObject::tr() |
QT_TR_NOOP() | QT_TR_NOOP() |
qsTranslate() | QCoreApplication::translate() |
QT_TRANSLATE_NOOP() | QT_TRANSLATE_NOOP() |
qsTrId() (since 4.7) | qtTrId() |
QT_TRID_NOOP() (since 4.7) | QT_TRID_NOOP() |
Definition at line 3536 of file qscriptengine.cpp.
Referenced by QDeclarativeScriptEngine::QDeclarativeScriptEngine().
bool QScriptEngine::isEvaluating | ( | ) | const |
Returns true if this engine is currently evaluating a script, otherwise returns false.
Definition at line 4191 of file qscriptengine.cpp.
Referenced by abortEvaluation(), and QScriptDebuggerCommandExecutor::execute().
QScriptValue QScriptEngine::newActivationObject | ( | ) |
Definition at line 2339 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newArray | ( | uint | length = 0 | ) |
Creates a QtScript object of class Array with the given length.
Definition at line 2426 of file qscriptengine.cpp.
Referenced by QDeclarativeInclude::callback(), QDeclarativeEnginePrivate::createQmlObject(), messageToScriptValue(), QDeclarativeWorkerScriptEnginePrivate::processMessage(), QDeclarativeObjectMethodScriptClass::property(), qDBusReplyToScriptValue(), qScriptValueFromSequence(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::newDate | ( | qsreal | value | ) |
Creates a QtScript object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC).
Definition at line 2452 of file qscriptengine.cpp.
Referenced by QScriptEnginePrivate::create(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::newDate | ( | const QDateTime & | value | ) |
Creates a QtScript object of class Date from the given value.
Definition at line 2464 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newFunction | ( | QScriptEngine::FunctionSignature | fun, |
int | length = 0 |
||
) |
Creates a QScriptValue that wraps a native (C++) function.
fun must be a C++ function with signature QScriptEngine::FunctionSignature. length is the number of arguments that fun expects; this becomes the length
property of the created QScriptValue.
Note that length only gives an indication of the number of arguments that the function expects; an actual invocation of a function can include any number of arguments. You can check the argumentCount() of the QScriptContext associated with the invocation to determine the actual number of arguments passed.
A prototype
property is automatically created for the resulting function object, to provide for the possibility that the function will be used as a constructor.
By combining newFunction() and the property flags QScriptValue::PropertyGetter and QScriptValue::PropertySetter, you can create script object properties that behave like normal properties in script code, but are in fact accessed through functions (analogous to how properties work in Qt's Property System). Example:
When the property foo
of the script object is subsequently accessed in script code, getSetFoo()
will be invoked to handle the access. In this particular case, we chose to store the "real" value of foo
as a property of the accessor function itself; you are of course free to do whatever you like in this function.
In the above example, a single native function was used to handle both reads and writes to the property; the argument count is used to determine if we are handling a read or write. You can also use two separate functions; just specify the relevant flag (QScriptValue::PropertyGetter or QScriptValue::PropertySetter) when setting the property, e.g.:
Definition at line 2389 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::assertFunction(), QScriptDebuggerBackend::fileNameFunction(), QDeclarativeWorkerScriptEnginePrivate::getWorker(), importExtension(), QScriptDebuggerBackend::lineNumberFunction(), NamedNodeMap::prototype(), NodeList::prototype(), Node::prototype(), Element::prototype(), Attr::prototype(), CharacterData::prototype(), Text::prototype(), Document::prototype(), QDeclarativeObjectMethodScriptClass::QDeclarativeObjectMethodScriptClass(), QDeclarativeObjectScriptClass::QDeclarativeObjectScriptClass(), QDeclarativeScriptEngine::QDeclarativeScriptEngine(), qmlsqldatabase_change_version(), qmlsqldatabase_executeSql(), qmlsqldatabase_open_sync(), qmlsqldatabase_transaction_shared(), QScriptDBusMessageConstructor::QScriptDBusMessageConstructor(), qt_add_qmlsqldatabase(), qt_add_qmlxmlhttprequest(), setupDBusInterface(), and QScriptDebuggerBackend::traceFunction().
QScriptValue QScriptEngine::newFunction | ( | QScriptEngine::FunctionSignature | fun, |
const QScriptValue & | prototype, | ||
int | length = 0 |
||
) |
Creates a constructor function from fun, with the given length.
The prototype
property of the resulting function is set to be the given prototype. The constructor
property of prototype is set to be the resulting function.
When a function is called as a constructor (e.g. new Foo()
), the `this' object associated with the function call is the new object that the function is expected to initialize; the prototype of this default constructed object will be the function's public prototype
property. If you always want the function to behave as a constructor (e.g. Foo()
should also create a new object), or if you need to create your own object rather than using the default `this' object, you should make sure that the prototype of your object is set correctly; either by setting it manually, or, when wrapping a custom type, by having registered the defaultPrototype() of that type. Example:
To wrap a custom type and provide a constructor for it, you'd typically do something like this:
Definition at line 2110 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newFunction | ( | QScriptEngine::FunctionWithArgSignature | fun, |
void * | arg | ||
) |
Definition at line 2407 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newObject | ( | ) |
Creates a QtScript object of class Object.
The prototype of the created object will be the Object prototype object.
Definition at line 2296 of file qscriptengine.cpp.
Referenced by QScript::__setupPackage__(), breakpointDataToScriptValue(), breakpointMapToScriptValue(), consoleCommandGroupDataToScriptValue(), consoleCommandGroupMapToScriptValue(), consoleCommandToScriptValue(), contextInfoToScriptValue(), NamedNodeMap::create(), NodeList::create(), Node::create(), QDeclarativeEnginePrivate::createQmlObject(), debuggerResponseToScriptValue(), debuggerScriptValuePropertyToScriptValue(), QDeclarativeGlobalScriptClass::explicitSetProperty(), QDeclarativeXmlListModel::get(), QDeclarativeWorkerScriptEnginePrivate::getWorker(), Document::load(), QDeclarativeItem::mapFromItem(), QDeclarativeItem::mapToItem(), newFunction(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), ModelNodeMetaObject::propertyWritten(), NamedNodeMap::prototype(), NodeList::prototype(), Node::prototype(), Element::prototype(), Attr::prototype(), CharacterData::prototype(), Text::prototype(), CDATA::prototype(), Document::prototype(), qDBusErrorToScriptValue(), QDeclarativeGlobalScriptClass::QDeclarativeGlobalScriptClass(), QDeclarativeScriptEngine::QDeclarativeScriptEngine(), qmlsqldatabase_change_version(), qmlsqldatabase_executeSql(), qmlsqldatabase_item(), qmlsqldatabase_open_sync(), qmlsqldatabase_transaction_shared(), qt_add_qmlsqldatabase(), qt_add_qmlxmlhttprequest(), QDeclarativeInclude::resultValue(), scriptDataToScriptValue(), scriptMapToScriptValue(), QScriptExtensionPlugin::setupPackage(), QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue(), and QDeclarativeInclude::worker_include().
QScriptValue QScriptEngine::newObject | ( | QScriptClass * | scriptClass, |
const QScriptValue & | data = QScriptValue() |
||
) |
Creates a QtScript Object of the given class, scriptClass.
The prototype of the created object will be the Object prototype object.
data, if specified, is set as the internal data of the new object (using QScriptValue::setData()).
Definition at line 2320 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newQMetaObject | ( | const QMetaObject * | metaObject, |
const QScriptValue & | ctor = QScriptValue() |
||
) |
Creates a QtScript object that represents a QObject class, using the the given metaObject and constructor ctor.
Enums of metaObject (declared with Q_ENUMS) 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.
Example:
Definition at line 2487 of file qscriptengine.cpp.
Referenced by QDBusConnectionConstructor::QDBusConnectionConstructor(), QDeclarativeScriptEngine::QDeclarativeScriptEngine(), QScriptDBusInterfaceConstructor::QScriptDBusInterfaceConstructor(), and QScriptDBusMessageConstructor::QScriptDBusMessageConstructor().
QScriptValue QScriptEngine::newQObject | ( | QObject * | object, |
ValueOwnership | ownership = QtOwnership , |
||
const QObjectWrapOptions & | options = 0 |
||
) |
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 a default prototype has been registered for the object's class (or its superclass, recursively), the prototype of the new script object will be set to be that default prototype.
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.
Definition at line 2221 of file qscriptengine.cpp.
Referenced by newQObject(), QScriptDebuggerScriptedConsoleCommand::parse(), QDBusConnectionConstructor::QDBusConnectionConstructor(), qmlxmlhttprequest_new(), QScriptDBusInterfaceConstructor::QScriptDBusInterfaceConstructor(), QScriptDBusMessageConstructor::QScriptDBusMessageConstructor(), setupDBusInterface(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::newQObject | ( | const QScriptValue & | scriptObject, |
QObject * | qtObject, | ||
ValueOwnership | ownership = QtOwnership , |
||
const QObjectWrapOptions & | options = 0 |
||
) |
Initializes the given scriptObject to hold the given qtObject, and returns the scriptObject.
This function enables you to "promote" a plain Qt Script object (created by the newObject() function) to a QObject proxy, or to replace the QObject contained inside an object previously created by the newQObject() function.
The prototype() of the scriptObject will remain unchanged.
If scriptObject is not an object, this function behaves like the normal newQObject(), i.e. it creates a new script object and returns it.
This function is useful when you want to provide a script constructor for a QObject-based class. If your constructor is invoked in a new
expression (QScriptContext::isCalledAsConstructor() returns true), you can pass QScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.
Definition at line 2260 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newRegExp | ( | const QRegExp & | regexp | ) |
Creates a QtScript object of class RegExp with the given regexp.
Definition at line 2134 of file qscriptengine.cpp.
Referenced by QScriptEnginePrivate::create(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::newRegExp | ( | const QString & | pattern, |
const QString & | flags | ||
) |
Creates a QtScript object of class RegExp with the given pattern and flags.
The legal flags are 'g' (global), 'i' (ignore case), and 'm' (multiline).
Definition at line 2440 of file qscriptengine.cpp.
QScriptValue QScriptEngine::newVariant | ( | const QVariant & | value | ) |
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.
Definition at line 2153 of file qscriptengine.cpp.
Referenced by QDeclarativeEnginePrivate::consoleLog(), NamedNodeMap::create(), NodeList::create(), Node::create(), do_dbus_call(), QDeclarativeEnginePrivate::formatDate(), QDeclarativeEnginePrivate::formatDateTime(), QDeclarativeEnginePrivate::formatTime(), Document::load(), messageToScriptValue(), ModelNodeMetaObject::propertyWritten(), qmlsqldatabase_change_version(), qmlsqldatabase_executeSql(), qmlsqldatabase_open_sync(), qmlsqldatabase_transaction_shared(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::newVariant | ( | const QScriptValue & | object, |
const QVariant & | value | ||
) |
Initializes the given Qt Script object to hold the given variant value, and returns the object.
This function enables you to "promote" a plain Qt Script object (created by the newObject() function) to a variant, or to replace the variant contained inside an object previously created by the newVariant() function.
The prototype() of the object will remain unchanged.
If object is not an object, this function behaves like the normal newVariant(), i.e. it creates a new script object and returns it.
This function is useful when you want to provide a script constructor for a C++ type. If your constructor is invoked in a new
expression (QScriptContext::isCalledAsConstructor() returns true), you can pass QScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.
Definition at line 2189 of file qscriptengine.cpp.
QScriptValue QScriptEngine::nullValue | ( | ) |
Returns a QScriptValue of the primitive type Null.
Definition at line 2068 of file qscriptengine.cpp.
Referenced by Node::attributes(), QDeclarativeEnginePrivate::createComponent(), QScriptDBusMessageConstructor::createErrorReply(), QDeclarativeEnginePrivate::createQmlObject(), QDeclarativeEnginePrivate::darker(), do_dbus_call(), Node::firstChild(), QDeclarativeWorkerScriptEnginePrivate::getWorker(), Node::lastChild(), QDeclarativeEnginePrivate::lighter(), Document::load(), QDeclarativeListScriptClass::newList(), QDeclarativeObjectScriptClass::newQObject(), Node::nextSibling(), Node::nodeValue(), Node::parentNode(), Node::previousSibling(), QDeclarativeObjectScriptClass::property(), qmlxmlhttprequest_responseXML(), QScriptDBusConnection::QScriptDBusConnection(), QDeclarativeEnginePrivate::tint(), QScriptDebuggerValue::toScriptValue(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().
QScriptValue QScriptEngine::objectById | ( | qint64 | id | ) | const |
Returns the object with the given id, or an invalid QScriptValue if there is no object with that id.
Definition at line 4424 of file qscriptengine.cpp.
Referenced by QJSDebuggerAgent::expandObjectById(), QJSDebuggerAgent::setProperty(), and QScriptDebuggerValue::toScriptValue().
void QScriptEngine::popContext | ( | ) |
Pops the current execution context and restores the previous one.
This function must be used in conjunction with pushContext().
Definition at line 2850 of file qscriptengine.cpp.
Referenced by QDeclarativeContextData::addImportedScript(), QScriptDebuggerBackend::doPendingEvaluate(), QDeclarativeExpressionPrivate::evalInObjectScope(), QDeclarativeInclude::finished(), importExtension(), QDeclarativeInclude::include(), QDeclarativeExpressionPrivate::init(), QDeclarativeWorkerScriptEnginePrivate::processLoad(), QDeclarativeExpressionPrivate::scriptValue(), and QDeclarativeInclude::worker_include().
int QScriptEngine::processEventsInterval | ( | ) | const |
Returns the interval in milliseconds between calls to QCoreApplication::processEvents() while the interpreter is running.
Definition at line 4174 of file qscriptengine.cpp.
QScriptContext * QScriptEngine::pushContext | ( | ) |
Enters a new execution context and returns the associated QScriptContext object.
Once you are done with the context, you should call popContext() to restore the old context.
By default, the `this' object of the new context is the Global Object. The context's callee() will be invalid.
This function is useful when you want to evaluate script code as if it were the body of a function. You can use the context's activationObject() to initialize local variables that will be available to scripts. Example:
In the above example, the new variable "tmp" defined in the script will be local to the context; in other words, the script doesn't have any effect on the global environment.
Returns 0 in case of stack overflow
Definition at line 2751 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::doPendingEvaluate(), and importExtension().
|
private |
Definition at line 3496 of file qscriptengine.cpp.
Referenced by qScriptRegisterMetaType_helper().
void QScriptEngine::reportAdditionalMemoryCost | ( | int | size | ) |
Reports an additional memory cost of the given size, measured in bytes, to the garbage collector.
This function can be called to indicate that a Qt Script object has memory associated with it that isn't managed by Qt Script itself. Reporting the additional cost makes it more likely that the garbage collector will be triggered.
Note that if the additional memory is shared with objects outside the scripting environment, the cost should not be reported, since collecting the Qt Script object would not cause the memory to be freed anyway.
Negative size values are ignored, i.e. this function can't be used to report that the additional memory has been deallocated.
Definition at line 4127 of file qscriptengine.cpp.
QScriptValue QScriptEngine::scriptValueFromQMetaObject | ( | ) |
Creates a QScriptValue that represents the Qt class T
.
This function is used in combination with one of the Q_SCRIPT_DECLARE_QMETAOBJECT() macro. Example:
Definition at line 295 of file qscriptengine.h.
void QScriptEngine::setAgent | ( | QScriptEngineAgent * | agent | ) |
Installs the given agent on this engine.
The agent will be notified of various events pertaining to script execution. This is useful when you want to find out exactly what the engine is doing, e.g. when evaluate() is called. The agent interface is the basis of tools like debuggers and profilers.
The engine maintains ownership of the agent.
Calling this function will replace the existing agent, if any.
Definition at line 4325 of file qscriptengine.cpp.
Referenced by QScriptDebuggerBackend::attachTo(), QScriptDebuggerBackend::detach(), QJSDebuggerAgent::QJSDebuggerAgent(), and QJSDebuggerAgent::~QJSDebuggerAgent().
void QScriptEngine::setDefaultPrototype | ( | int | metaTypeId, |
const QScriptValue & | prototype | ||
) |
Sets the default prototype of the C++ type identified by 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.
The prototype object itself may be constructed using one of two principal techniques; the simplest is to subclass QScriptable, which enables you to define the scripting API of the type through QObject properties and slots. Another possibility is to create a script object by calling newObject(), and populate the object with the desired properties (e.g. native functions wrapped with newFunction()).
Definition at line 3010 of file qscriptengine.cpp.
Referenced by QScriptDBusMessageConstructor::QScriptDBusMessageConstructor().
void QScriptEngine::setGlobalObject | ( | const QScriptValue & | object | ) |
Sets this engine's Global Object to be the given object.
If object is not a valid script object, this function does nothing.
When setting a custom global object, you may want to use QScriptValueIterator to copy the properties of the standard Global Object; alternatively, you can set the internal prototype of your custom object to be the original Global Object.
Definition at line 2053 of file qscriptengine.cpp.
Referenced by QDeclarativeGlobalScriptClass::explicitSetProperty(), QScriptDebuggerScriptedConsoleCommandJob::handleResponse(), QScriptDebuggerScriptedConsoleCommand::parse(), QDeclarativeGlobalScriptClass::QDeclarativeGlobalScriptClass(), QScriptContext::setThisObject(), and QScriptDebuggerScriptedConsoleCommandJob::start().
void QScriptEngine::setProcessEventsInterval | ( | int | interval | ) |
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.
You can use QCoreApplication::postEvent() to post an event that performs custom processing at the next interval. For example, you could keep track of the total running time of the script and call abortEvaluation() when you detect that the script has been running for a long time without completing.
Definition at line 4156 of file qscriptengine.cpp.
|
signal |
This signal is emitted when a script function connected to a signal causes an exception.
QScriptValue QScriptEngine::toObject | ( | const QScriptValue & | value | ) |
Converts the given value to an object, if such a conversion is possible; otherwise returns an invalid QScriptValue.
The conversion is performed according to the following table:
Input Type | Result |
Undefined | An invalid QScriptValue. |
Null | An invalid QScriptValue. |
Boolean | A new Boolean object whose internal value is set to the value of the boolean. |
Number | A new Number object whose internal value is set to the value of the number. |
String | A new String object whose internal value is set to the value of the string. |
Object | The result is the object itself (no conversion). |
Definition at line 4401 of file qscriptengine.cpp.
Referenced by abortEvaluation(), and QScriptValue::toObject().
|
inline |
Creates a QScriptValue with the given value.
Note that the template type T
must be known to QMetaType.
See Conversion Between QtScript and C++ Types for a description of the built-in type conversion provided by QtScript. By default, the types that are not specially handled by QtScript are represented as QVariants (e.g. the value is passed to newVariant()); you can change this behavior by installing your own type conversion functions with qScriptRegisterMetaType().
Definition at line 213 of file qscriptengine.h.
Referenced by breakpointMapToScriptValue(), consoleCommandGroupMapToScriptValue(), consoleCommandToScriptValue(), QDeclarativeEnginePrivate::darker(), debuggerResponseToScriptValue(), debuggerScriptValuePropertyToScriptValue(), QDeclarativeXmlListModel::get(), QScriptDebuggerScriptedConsoleCommandJob::handleResponse(), QDeclarativeEnginePrivate::hsla(), QDeclarativeEnginePrivate::lighter(), FlatListScriptClass::property(), qScriptValueFromSequence(), QDeclarativeEnginePrivate::rgba(), scriptMapToScriptValue(), and QDeclarativeEnginePrivate::tint().
QScriptString QScriptEngine::toStringHandle | ( | const QString & | str | ) |
Returns a handle that represents the given string, str.
QScriptString can be used to quickly look up properties, and compare property names, of script objects.
Definition at line 4372 of file qscriptengine.cpp.
Referenced by QDeclarativeSqlQueryScriptClass::QDeclarativeSqlQueryScriptClass().
QScriptValue QScriptEngine::uncaughtException | ( | ) | const |
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.
Definition at line 2910 of file qscriptengine.cpp.
Referenced by QDeclarativeExpressionPrivate::exceptionToError(), QDeclarativeInclude::finished(), importExtension(), QDeclarativeInclude::include(), uncaughtExceptionBacktrace(), uncaughtExceptionLineNumber(), and QDeclarativeInclude::worker_include().
QStringList QScriptEngine::uncaughtExceptionBacktrace | ( | ) | const |
Returns a human-readable backtrace of the last uncaught exception.
It is in the form <function-name>()<file-name>:<line-number>
.
Definition at line 2944 of file qscriptengine.cpp.
int QScriptEngine::uncaughtExceptionLineNumber | ( | ) | const |
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().
Definition at line 2930 of file qscriptengine.cpp.
Referenced by QDeclarativeExpressionPrivate::exceptionToError(), and QScriptDebuggerScriptedConsoleCommand::parse().
QScriptValue QScriptEngine::undefinedValue | ( | ) |
Returns a QScriptValue of the primitive type Undefined.
Definition at line 2079 of file qscriptengine.cpp.
Referenced by Node::attributes(), Node::childNodes(), QDeclarativeObjectMethodScriptClass::connect(), consoleCommandToScriptValue(), QDeclarativeObjectScriptClass::destroy(), QDeclarativeObjectMethodScriptClass::disconnect(), Document::documentElement(), QScriptDebuggerBackendPrivate::fileName(), Node::firstChild(), FlatListModel::get(), QDeclarativeXmlListModel::get(), NestedListModel::get(), importExtension(), QDeclarativeInclude::include(), Text::isElementContentWhitespace(), Node::lastChild(), NamedNodeMap::length(), NodeList::length(), CharacterData::length(), Attr::name(), QDeclarativeObjectScriptClass::newQObject(), Node::nextSibling(), Node::nodeName(), Node::nodeType(), Node::nodeValue(), QDeclarativeWorkerScriptEnginePrivate::onMessage(), Attr::ownerElement(), Node::parentNode(), Node::previousSibling(), QDeclarativeObjectMethodScriptClass::property(), QDeclarativeSqlQueryScriptClass::property(), qmlsqldatabase_change_version(), qmlsqldatabase_item(), qmlsqldatabase_open_sync(), qmlsqldatabase_transaction_shared(), qmlxmlhttprequest_new(), qmlxmlhttprequest_setRequestHeader(), QDeclarativeWorkerScriptEnginePrivate::sendMessage(), QScriptDebuggerValue::toScriptValue(), QScriptDebuggerBackendPrivate::trace(), Attr::value(), Text::wholeText(), QDeclarativeInclude::worker_include(), Document::xmlEncoding(), Document::xmlStandalone(), and Document::xmlVersion().
|
related |
The function signature QScriptValue f(QScriptContext *, QScriptEngine *)
.
A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.
|
related |
The function signature QScriptValue f(QScriptContext *, QScriptEngine *, void *)
.
A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.
|
related |
Creates a connection from the signal in the sender to the given function.
If receiver is an object, it will act as the `this' object when the signal handler function is invoked. Returns true if the connection succeeds; otherwise returns false.
Definition at line 4242 of file qscriptengine.cpp.
|
related |
Disconnects the signal in the sender from the given (receiver, function) pair.
Returns true if the connection is successfully broken; otherwise returns false.
Definition at line 4272 of file qscriptengine.cpp.
|
related |
Registers the type T
in the given engine. toScriptValue must be a function that will convert from a value of type T
to a QScriptValue, and fromScriptValue a function that does the opposite. prototype, if valid, is the prototype that's set on QScriptValues returned by toScriptValue.
Returns the internal ID used by QMetaType.
You only need to call this function if you want to provide custom conversion of values of type T
, i.e. if the default QVariant-based representation and conversion is not appropriate. (Note that custom QObject-derived types also fall in this category; e.g. for a QObject-derived class called MyObject, you probably want to define conversion functions for MyObject* that utilize QScriptEngine::newQObject() and QScriptValue::toQObject().)
If you only want to define a common script interface for values of type T
, and don't care how those values are represented (i.e. storing them in QVariants is fine), use setDefaultPrototype() instead; this will minimize conversion costs.
You need to declare the custom type first with Q_DECLARE_METATYPE().
After a type has been registered, you can convert from a QScriptValue to that type using fromScriptValue(), and create a QScriptValue from a value of that type using toScriptValue(). The engine will take care of calling the proper conversion function when calling C++ slots, and when getting or setting a C++ property; i.e. the custom type may be used seamlessly on both the C++ side and the script side.
The following is an example of how to use this function. We will specify custom conversion of our type MyStruct
. Here's the C++ type:
We must declare it so that the type will be known to QMetaType:
Next, the MyStruct
conversion functions. We represent the MyStruct
value as a script object and just copy the properties:
Now we can register MyStruct
with the engine:
Working with MyStruct
values is now easy:
If you want to be able to construct values of your custom type from script code, you have to register a constructor function for the type. For example:
Definition at line 380 of file qscriptengine.h.
|
friend |
Definition at line 371 of file qscriptengine.h.
|
related |
Registers the sequence type T
in the given engine. This function provides conversion functions that convert between T
and Qt Script Array
objects. T
must provide a const_iterator class and begin(), end() and push_back() functions. If prototype is valid, it will be set as the prototype of Array
objects due to conversion from T
; otherwise, the standard Array
prototype will be used.
Returns the internal ID used by QMetaType.
You need to declare the container type first with Q_DECLARE_METATYPE(). If the element type isn't a standard Qt/C++ type, it must be declared using Q_DECLARE_METATYPE() as well. Example:
Definition at line 424 of file qscriptengine.h.
|
friend |
Definition at line 338 of file qscriptengine.h.
|
related |
Uses engine to create a QScriptValue that represents the Qt class T
.
This function is equivalent to QScriptEngine::scriptValueFromQMetaObject().
Definition at line 305 of file qscriptengine.h.
|
related |
Creates an array in the form of a QScriptValue using the given engine with the given container of template type Container
.
The Container
type must provide a const_iterator
class to enable the contents of the container to be copied into the array.
Additionally, the type of each element in the sequence should be suitable for conversion to a QScriptValue. See Conversion Between QtScript and C++ Types for more information about the restrictions on types that can be used with QScriptValue.
Definition at line 401 of file qscriptengine.h.
|
related |
Creates a QScriptValue using the given engine with the given value of template type T
.
This function is equivalent to QScriptEngine::toScriptValue().
Definition at line 327 of file qscriptengine.h.
Referenced by qscriptQMetaObjectConstructor().
|
friend |
Definition at line 318 of file qscriptengine.h.
|
related |
Copies the elements in the sequence specified by value to the given container of template type Container
.
The value used is typically an array, but any container can be copied as long as it provides a length
property describing how many elements it contains.
Additionally, the type of each element in the sequence must be suitable for conversion to a C++ type from a QScriptValue. See Conversion Between QtScript and C++ Types for more information about the restrictions on types that can be used with QScriptValue.
Definition at line 414 of file qscriptengine.h.
|
related |
Returns the given value converted to the template type T
.
This function is equivalent to QScriptEngine::fromScriptValue().
Definition at line 365 of file qscriptengine.h.