Qt 4.8
Public Types | Signals | Public Functions | Static Public Functions | Protected Functions | Private Functions | Static Private Functions | Friends | Related Functions | List of all members
QScriptEngine Class Reference

The QScriptEngine class provides an environment for evaluating Qt Script code. More...

#include <qscriptengine.h>

Inheritance diagram for QScriptEngine:
QObject QDeclarativeScriptEngine QDeclarativeWorkerScriptEnginePrivate::ScriptEngine

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...
 
QScriptEngineAgentagent () 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...
 
QScriptContextcurrentContext () 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 >
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 &regexp)
 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...
 
QScriptContextpushContext ()
 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 QObjectListchildren () 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< QByteArraydynamicPropertyNames () 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 >
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 QMetaObjectmetaObject () 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
 
QObjectparent () 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...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (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...
 
QObjectsender () 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...
 
qScriptValueToValue (const QScriptValue &value)
 Returns the given value converted to the template type T. 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< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QScriptEngine class provides an environment for evaluating Qt Script code.

Since
4.3
Note
This class or function is reentrant.

See the QtScript documentation for information about the Qt Script language, and how to get started with scripting your C++ application.

Evaluating Scripts

Use evaluate() to evaluate script code; this is the C++ equivalent of the built-in script function eval().

QScriptEngine myEngine;
QScriptValue three = myEngine.evaluate("1 + 2");

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():

QScriptValue fun = myEngine.evaluate("(function(a, b) { return a + b; })");
args << 1 << 2;
QScriptValue threeAgain = fun.call(QScriptValue(), args);

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():

QString fileName = "helloworld.qs";
QFile scriptFile(fileName);
if (!scriptFile.open(QIODevice::ReadOnly))
// handle error
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
myEngine.evaluate(contents, fileName);

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

Engine Configuration

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:

myEngine.globalObject().setProperty("myNumber", 123);
...
QScriptValue myNumberPlusOne = myEngine.evaluate("myNumber + 1");

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

Script Exceptions

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.

QScriptValue result = myEngine.evaluate(...);
if (myEngine.hasUncaughtException()) {
int line = myEngine.uncaughtExceptionLineNumber();
qDebug() << "uncaught exception at line" << line << ":" << result.toString();
}

The checkSyntax() function can be used to determine whether code can be usefully passed to evaluate().

Script Object Creation

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.

QObject Integration

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.

QPushButton button;
QScriptValue scriptButton = myEngine.newQObject(&button);
myEngine.globalObject().setProperty("button", scriptButton);
myEngine.evaluate("button.checkable = true");
qDebug() << scriptButton.property("checkable").toBoolean();
scriptButton.property("show").call(); // call the show() slot

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

++-Types

Support for Custom C++ Types

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.

Importing Extensions

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.

Native Functions

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:

QScriptValue myAdd(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue a = context->argument(0);
QScriptValue b = context->argument(1);
return 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)");

Long-running Scripts

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

Garbage Collection

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.

/Tracing-Facilities

Core Debugging/Tracing Facilities

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.

See also
QScriptValue, QScriptContext, QScriptEngineAgent

Definition at line 104 of file qscriptengine.h.

Typedefs

◆ DemarshalFunction

QScriptEngine::DemarshalFunction
Warning
This function is not part of the public interface.

Definition at line 208 of file qscriptengine.h.

◆ FunctionSignature

typedef QScriptValue(* QScriptEngine::FunctionSignature) (QScriptContext *, QScriptEngine *)

Definition at line 165 of file qscriptengine.h.

◆ FunctionWithArgSignature

typedef QScriptValue(* QScriptEngine::FunctionWithArgSignature) (QScriptContext *, QScriptEngine *, void *)

Definition at line 166 of file qscriptengine.h.

◆ MarshalFunction

QScriptEngine::MarshalFunction
Warning
This function is not part of the public interface.

Definition at line 207 of file qscriptengine.h.

Enumerations

◆ QObjectWrapOption

These flags specify options when wrapping a QObject pointer with newQObject().

  • ExcludeChildObjects The script object will not expose child objects as properties.
  • ExcludeSuperClassMethods The script object will not expose signals and slots inherited from the superclass.
  • ExcludeSuperClassProperties The script object will not expose properties inherited from the superclass.
  • ExcludeSuperClassContents Shorthand form for ExcludeSuperClassMethods | ExcludeSuperClassProperties
  • ExcludeDeleteLater The script object will not expose the QObject::deleteLater() slot.
  • ExcludeSlots The script object will not expose the QObject's slots.
  • AutoCreateDynamicProperties 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.
  • PreferExistingWrapperObject If a wrapper object with the requested configuration already exists, return that object.
  • SkipMethodsInEnumeration Don't include methods (signals and slots) when enumerating the object's properties.
Enumerator
ExcludeChildObjects 
ExcludeSuperClassMethods 
ExcludeSuperClassProperties 
ExcludeSuperClassContents 
SkipMethodsInEnumeration 
ExcludeDeleteLater 
ExcludeSlots 
AutoCreateDynamicProperties 
PreferExistingWrapperObject 

Definition at line 119 of file qscriptengine.h.

◆ ValueOwnership

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.

Constructors and Destructors

◆ QScriptEngine() [1/3]

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

1985  : QObject(*new QScriptEnginePrivate, 0)
1986 {
1987 }
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ QScriptEngine() [2/3]

QScriptEngine::QScriptEngine ( QObject parent)
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.

1997  : QObject(*new QScriptEnginePrivate, parent)
1998 {
1999 }
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ ~QScriptEngine()

QScriptEngine::~QScriptEngine ( )
virtual

Destroys this QScriptEngine.

Definition at line 2012 of file qscriptengine.cpp.

2013 {
2014 #ifdef QT_NO_QOBJECT
2015  delete d_ptr;
2016  d_ptr = 0;
2017 #endif
2018 }
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320

◆ QScriptEngine() [3/3]

QScriptEngine::QScriptEngine ( QScriptEnginePrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 2003 of file qscriptengine.cpp.

2004  : QObject(dd, parent)
2005 {
2006 }
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

Functions

◆ abortEvaluation()

void QScriptEngine::abortEvaluation ( const QScriptValue result = QScriptValue())

Aborts any script evaluation currently taking place in this engine.

Since
4.4

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.

See also
evaluate(), isEvaluating(), setProcessEventsInterval()

Definition at line 4216 of file qscriptengine.cpp.

4217 {
4218  Q_D(QScriptEngine);
4219  if (!isEvaluating())
4220  return;
4221  d->abortResult = result;
4222  d->timeoutChecker()->setShouldAbort(true);
4223  JSC::throwError(d->currentFrame, JSC::createInterruptedExecutionException(&d->currentFrame->globalData()).toObject(d->currentFrame));
4224 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
bool isEvaluating() const
Returns true if this engine is currently evaluating a script, otherwise returns false.
QScriptValue toObject(const QScriptValue &value)
Converts the given value to an object, if such a conversion is possible; otherwise returns an invalid...

◆ agent()

QScriptEngineAgent * QScriptEngine::agent ( ) const

Returns the agent currently installed on this engine, or 0 if no agent is installed.

Since
4.4
See also
setAgent()

Definition at line 4353 of file qscriptengine.cpp.

Referenced by QScriptDebuggerBackend::detach(), popContext(), QScriptDeclarativeClass::pushCleanContext(), pushContext(), and setAgent().

4354 {
4355  Q_D(const QScriptEngine);
4356  return d->activeAgent;
4357 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ availableExtensions()

QStringList QScriptEngine::availableExtensions ( ) const

Returns a list naming the available extensions that can be imported using the importExtension() function.

Since
4.4

This list includes extensions that have been imported.

See also
importExtension(), importedExtensions()

Definition at line 3754 of file qscriptengine.cpp.

3755 {
3756 #if defined(QT_NO_QOBJECT) || defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
3757  return QStringList();
3758 #else
3760  if (!app)
3761  return QStringList();
3762 
3763  QSet<QString> result;
3764 
3765  QObjectList staticPlugins = QPluginLoader::staticInstances();
3766  for (int i = 0; i < staticPlugins.size(); ++i) {
3768  iface = qobject_cast<QScriptExtensionInterface*>(staticPlugins.at(i));
3769  if (iface) {
3770  QStringList keys = iface->keys();
3771  for (int j = 0; j < keys.count(); ++j)
3772  result << keys.at(j);
3773  }
3774  }
3775 
3776  QStringList libraryPaths = app->libraryPaths();
3777  for (int i = 0; i < libraryPaths.count(); ++i) {
3778  QString libPath = libraryPaths.at(i) + QDir::separator() + QLatin1String("script");
3779  QDir dir(libPath);
3780  if (!dir.exists())
3781  continue;
3782 
3783  // look for C++ plugins
3784  QFileInfoList files = dir.entryInfoList(QDir::Files);
3785  for (int j = 0; j < files.count(); ++j) {
3786  QFileInfo entry = files.at(j);
3787  QString filePath = entry.canonicalFilePath();
3788  QPluginLoader loader(filePath);
3790  iface = qobject_cast<QScriptExtensionInterface*>(loader.instance());
3791  if (iface) {
3792  QStringList keys = iface->keys();
3793  for (int k = 0; k < keys.count(); ++k)
3794  result << keys.at(k);
3795  }
3796  }
3797 
3798  // look for scripts
3799  QString initDotJs = QLatin1String("__init__.js");
3800  QList<QFileInfo> stack;
3801  stack << dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
3802  while (!stack.isEmpty()) {
3803  QFileInfo entry = stack.takeLast();
3804  QDir dd(entry.canonicalFilePath());
3805  if (dd.exists(initDotJs)) {
3806  QString rpath = dir.relativeFilePath(dd.canonicalPath());
3807  QStringList components = rpath.split(QLatin1Char('/'));
3808  result << components.join(QLatin1String("."));
3809  stack << dd.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
3810  }
3811  }
3812  }
3813 
3814  QStringList lst = result.toList();
3815  qSort(lst);
3816  return lst;
3817 #endif
3818 }
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
The QString class provides a Unicode character string.
Definition: qstring.h:83
T * qobject_cast(QObject *object)
Definition: qobject.h:375
static QChar separator()
Returns the native directory separator: "/" under Unix (including Mac OS X) and "\\" under Windows...
Definition: qdir.cpp:1831
static QObjectList staticInstances()
Returns a list of static plugin instances (root components) held by the plugin loader.
QStringList keys
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
QList< T > toList() const
Definition: qset.h:296
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QString canonicalFilePath() const
Returns the canonical path including the file name, i.e.
Definition: qfileinfo.cpp:551
void qSort(RandomAccessIterator start, RandomAccessIterator end)
Definition: qalgorithms.h:177
QString join(const QString &sep) const
Joins all the string list&#39;s strings into a single string with each element separated by the given sep...
Definition: qstringlist.h:162
The QCoreApplication class provides an event loop for console Qt applications.
virtual QStringList keys() const =0
static QCoreApplication * instance()
Returns a pointer to the application&#39;s QCoreApplication (or QApplication) instance.
static QStringList libraryPaths()
Returns a list of paths that the application will search when dynamically loading libraries...
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
T takeLast()
Removes the last item in the list and returns it.
Definition: qlist.h:492
QStringList split(const QString &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const Q_REQUIRED_RESULT
Splits the string into substrings wherever sep occurs, and returns the list of those strings...
Definition: qstring.cpp:6526
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
The QPluginLoader class loads a plugin at run-time.
Definition: qpluginloader.h:62

◆ canEvaluate()

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

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(), checkSyntax()

Definition at line 2592 of file qscriptengine.cpp.

2593 {
2594  return QScriptEnginePrivate::canEvaluate(program);
2595 }
static bool canEvaluate(const QString &program)

◆ checkSyntax()

QScriptSyntaxCheckResult QScriptEngine::checkSyntax ( const QString program)
static

◆ clearExceptions()

void QScriptEngine::clearExceptions ( )

Clears any uncaught exceptions in this engine.

Since
4.4
See also
hasUncaughtException()

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

2971 {
2972  Q_D(QScriptEngine);
2973  JSC::ExecState* exec = d->currentFrame;
2974  exec->clearException();
2975  d->clearCurrentException();
2976 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ collectGarbage()

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.

See also
reportAdditionalMemoryCost()

Definition at line 4097 of file qscriptengine.cpp.

4098 {
4099  Q_D(QScriptEngine);
4100  d->collectGarbage();
4101 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ convert()

bool QScriptEngine::convert ( const QScriptValue value,
int  type,
void *  ptr 
)
private
Warning
This function is not part of the public interface.

Definition at line 3461 of file qscriptengine.cpp.

3462 {
3463  Q_D(QScriptEngine);
3464  QScript::APIShim shim(d);
3465  return QScriptEnginePrivate::convertValue(d->currentFrame, d->scriptValueToJSCValue(value), type, ptr);
3466 }
double d
Definition: qnumeric_p.h:62
int type
Definition: qmetatype.cpp:239
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
const T * ptr(const T &t)
static bool convertValue(JSC::ExecState *, JSC::JSValue value, int type, void *ptr)

◆ convertV2()

bool QScriptEngine::convertV2 ( const QScriptValue value,
int  type,
void *  ptr 
)
staticprivate
Warning
This function is not part of the public interface.

Definition at line 3471 of file qscriptengine.cpp.

Referenced by qscriptvalue_cast_helper().

3472 {
3474  if (vp) {
3475  switch (vp->type) {
3477  if (vp->engine) {
3478  QScript::APIShim shim(vp->engine);
3480  } else {
3482  }
3483  }
3488  }
3489  }
3490  return false;
3491 }
int type
Definition: qmetatype.cpp:239
static bool convertString(const QString &, int type, void *ptr)
static QScriptValuePrivate * get(const QScriptValue &q)
JSC::ExecState * currentFrame
const T * ptr(const T &t)
static bool convertValue(JSC::ExecState *, JSC::JSValue value, int type, void *ptr)
JSC::JSValue jscValue
static bool convertNumber(qsreal, int type, void *ptr)
QScriptEnginePrivate * engine

◆ create()

QScriptValue QScriptEngine::create ( int  type,
const void *  ptr 
)
private
Warning
This function is not part of the public interface.

Definition at line 3049 of file qscriptengine.cpp.

Referenced by QScriptEnginePrivate::create(), and qScriptValueFromValue_helper().

3050 {
3051  Q_D(QScriptEngine);
3052  QScript::APIShim shim(d);
3053  return d->scriptValueFromJSCValue(d->create(d->currentFrame, type, ptr));
3054 }
double d
Definition: qnumeric_p.h:62
int type
Definition: qmetatype.cpp:239
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
const T * ptr(const T &t)

◆ currentContext()

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

2721 {
2722  Q_D(const QScriptEngine);
2723  return const_cast<QScriptEnginePrivate*>(d)->contextForFrame(d->currentFrame);
2724 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ defaultPrototype()

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.

See also
setDefaultPrototype()

Definition at line 2984 of file qscriptengine.cpp.

2985 {
2986  Q_D(const QScriptEngine);
2987  return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(d->defaultPrototype(metaTypeId));
2988 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ evaluate() [1/2]

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.

See also
canEvaluate(), hasUncaughtException(), isEvaluating(), abortEvaluation()

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

2672 {
2673  Q_D(QScriptEngine);
2674  QScript::APIShim shim(d);
2675  WTF::PassRefPtr<QScript::UStringSourceProviderWithFeedback> provider
2676  = QScript::UStringSourceProviderWithFeedback::create(program, fileName, lineNumber, d);
2677  intptr_t sourceId = provider->asID();
2678  JSC::SourceCode source(provider, lineNumber); //after construction of SourceCode provider variable will be null.
2679 
2680  JSC::ExecState* exec = d->currentFrame;
2681  WTF::RefPtr<JSC::EvalExecutable> executable = JSC::EvalExecutable::create(exec, source);
2682  bool compile = true;
2683  return d->scriptValueFromJSCValue(d->evaluateHelper(exec, sourceId, executable.get(), compile));
2684 }
double d
Definition: qnumeric_p.h:62
static Expression::Ptr create(Expression *const expr, const YYLTYPE &sourceLocator, const ParserContext *const parseInfo)
static PassRefPtr< UStringSourceProviderWithFeedback > create(const JSC::UString &source, const JSC::UString &url, int lineNumber, QScriptEnginePrivate *engine)
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
INT_PTR intptr_t

◆ evaluate() [2/2]

QScriptValue QScriptEngine::evaluate ( const QScriptProgram program)

Evaluates the given program and returns the result of the evaluation.

Since
4.7

Definition at line 2695 of file qscriptengine.cpp.

2696 {
2697  Q_D(QScriptEngine);
2698  QScriptProgramPrivate *program_d = QScriptProgramPrivate::get(program);
2699  if (!program_d)
2700  return QScriptValue();
2701 
2702  QScript::APIShim shim(d);
2703  JSC::ExecState* exec = d->currentFrame;
2704  JSC::EvalExecutable *executable = program_d->executable(exec, d);
2705  bool compile = !program_d->isCompiled;
2706  JSC::JSValue result = d->evaluateHelper(exec, program_d->sourceId,
2707  executable, compile);
2708  if (compile)
2709  program_d->isCompiled = true;
2710  return d->scriptValueFromJSCValue(result);
2711 }
double d
Definition: qnumeric_p.h:62
JSC::EvalExecutable * executable(JSC::ExecState *exec, QScriptEnginePrivate *engine)
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
static QScriptProgramPrivate * get(const QScriptProgram &q)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ fromScriptValue()

template<typename T >
T QScriptEngine::fromScriptValue ( const QScriptValue value)
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.

See also
toScriptValue(), qScriptRegisterMetaType()

Definition at line 218 of file qscriptengine.h.

219  {
220  return qscriptvalue_cast<T>(value);
221  }
T qscriptvalue_cast(const QScriptValue &)

◆ globalObject()

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

2031 {
2032  Q_D(const QScriptEngine);
2033  QScript::APIShim shim(const_cast<QScriptEnginePrivate*>(d));
2034  JSC::JSObject *result = d->globalObject();
2035  return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(result);
2036 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ hasUncaughtException()

bool QScriptEngine::hasUncaughtException ( ) const

◆ importedExtensions()

QStringList QScriptEngine::importedExtensions ( ) const

Returns a list naming the extensions that have been imported using the importExtension() function.

Since
4.4
See also
availableExtensions()

Definition at line 3831 of file qscriptengine.cpp.

3832 {
3833  Q_D(const QScriptEngine);
3834  QStringList lst = d->importedExtensions.toList();
3835  qSort(lst);
3836  return lst;
3837 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
void qSort(RandomAccessIterator start, RandomAccessIterator end)
Definition: qalgorithms.h:177

◆ importExtension()

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

See also
availableExtensions(), QScriptExtensionPlugin, {Creating QtScript Extensions}

Definition at line 3572 of file qscriptengine.cpp.

3573 {
3574 #if defined(QT_NO_QOBJECT) || defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
3575  Q_UNUSED(extension);
3576 #else
3577  Q_D(QScriptEngine);
3578  QScript::APIShim shim(d);
3579  if (d->importedExtensions.contains(extension))
3580  return undefinedValue(); // already imported
3581 
3582  QScriptContext *context = currentContext();
3584  if (!app)
3585  return context->throwError(QLatin1String("No application object"));
3586 
3587  QObjectList staticPlugins = QPluginLoader::staticInstances();
3588  QStringList libraryPaths = app->libraryPaths();
3589  QString dot = QLatin1String(".");
3590  QStringList pathComponents = extension.split(dot);
3591  QString initDotJs = QLatin1String("__init__.js");
3592 
3593  QString ext;
3594  for (int i = 0; i < pathComponents.count(); ++i) {
3595  if (!ext.isEmpty())
3596  ext.append(dot);
3597  ext.append(pathComponents.at(i));
3598  if (d->importedExtensions.contains(ext))
3599  continue; // already imported
3600 
3601  if (d->extensionsBeingImported.contains(ext)) {
3602  return context->throwError(QString::fromLatin1("recursive import of %0")
3603  .arg(extension));
3604  }
3605  d->extensionsBeingImported.insert(ext);
3606 
3607  QScriptExtensionInterface *iface = 0;
3608  QString initjsContents;
3609  QString initjsFileName;
3610 
3611  // look for the extension in static plugins
3612  for (int j = 0; j < staticPlugins.size(); ++j) {
3613  iface = qobject_cast<QScriptExtensionInterface*>(staticPlugins.at(j));
3614  if (!iface)
3615  continue;
3616  if (iface->keys().contains(ext))
3617  break; // use this one
3618  else
3619  iface = 0; // keep looking
3620  }
3621 
3622  {
3623  // look for __init__.js resource
3624  QString path = QString::fromLatin1(":/qtscriptextension");
3625  for (int j = 0; j <= i; ++j) {
3626  path.append(QLatin1Char('/'));
3627  path.append(pathComponents.at(j));
3628  }
3629  path.append(QLatin1Char('/'));
3630  path.append(initDotJs);
3631  QFile file(path);
3632  if (file.open(QIODevice::ReadOnly)) {
3633  QTextStream ts(&file);
3634  initjsContents = ts.readAll();
3635  initjsFileName = path;
3636  file.close();
3637  }
3638  }
3639 
3640  if (!iface && initjsContents.isEmpty()) {
3641  // look for the extension in library paths
3642  for (int j = 0; j < libraryPaths.count(); ++j) {
3643  QString libPath = libraryPaths.at(j) + QDir::separator() + QLatin1String("script");
3644  QDir dir(libPath);
3645  if (!dir.exists(dot))
3646  continue;
3647 
3648  // look for C++ plugin
3649  QFileInfoList files = dir.entryInfoList(QDir::Files);
3650  for (int k = 0; k < files.count(); ++k) {
3651  QFileInfo entry = files.at(k);
3652  QString filePath = entry.canonicalFilePath();
3653  QPluginLoader loader(filePath);
3654  iface = qobject_cast<QScriptExtensionInterface*>(loader.instance());
3655  if (iface) {
3656  if (iface->keys().contains(ext))
3657  break; // use this one
3658  else
3659  iface = 0; // keep looking
3660  }
3661  }
3662 
3663  // look for __init__.js in the corresponding dir
3664  QDir dirdir(libPath);
3665  bool dirExists = dirdir.exists();
3666  for (int k = 0; dirExists && (k <= i); ++k)
3667  dirExists = dirdir.cd(pathComponents.at(k));
3668  if (dirExists && dirdir.exists(initDotJs)) {
3669  QFile file(dirdir.canonicalPath()
3670  + QDir::separator() + initDotJs);
3671  if (file.open(QIODevice::ReadOnly)) {
3672  QTextStream ts(&file);
3673  initjsContents = ts.readAll();
3674  initjsFileName = file.fileName();
3675  file.close();
3676  }
3677  }
3678 
3679  if (iface || !initjsContents.isEmpty())
3680  break;
3681  }
3682  }
3683 
3684  if (!iface && initjsContents.isEmpty()) {
3685  d->extensionsBeingImported.remove(ext);
3686  return context->throwError(
3687  QString::fromLatin1("Unable to import %0: no such extension")
3688  .arg(extension));
3689  }
3690 
3691  // initialize the extension in a new context
3693  ctx->setThisObject(globalObject());
3694  ctx->activationObject().setProperty(QLatin1String("__extension__"), ext,
3696  ctx->activationObject().setProperty(QLatin1String("__setupPackage__"),
3699 
3700  // the script is evaluated first
3701  if (!initjsContents.isEmpty()) {
3702  QScriptValue ret = evaluate(initjsContents, initjsFileName);
3703  if (hasUncaughtException()) {
3704  popContext();
3705  d->extensionsBeingImported.remove(ext);
3706  return ret;
3707  }
3708  }
3709 
3710  // next, the C++ plugin is called
3711  if (iface) {
3712  iface->initialize(ext, this);
3713  if (hasUncaughtException()) {
3714  QScriptValue ret = uncaughtException(); // ctx_p->returnValue();
3715  popContext();
3716  d->extensionsBeingImported.remove(ext);
3717  return ret;
3718  }
3719  }
3720 
3721  // if the __postInit__ function has been set, we call it
3722  QScriptValue postInit = ctx->activationObject().property(QLatin1String("__postInit__"));
3723  if (postInit.isFunction()) {
3724  postInit.call(globalObject());
3725  if (hasUncaughtException()) {
3726  QScriptValue ret = uncaughtException(); // ctx_p->returnValue();
3727  popContext();
3728  d->extensionsBeingImported.remove(ext);
3729  return ret;
3730  }
3731  }
3732 
3733  popContext();
3734 
3735  d->importedExtensions.insert(ext);
3736  d->extensionsBeingImported.remove(ext);
3737  } // for (i)
3738 #endif // QT_NO_QOBJECT
3739  return undefinedValue();
3740 }
QScriptValue newFunction(FunctionSignature signature, int length=0)
Creates a QScriptValue that wraps a native (C++) function.
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
double d
Definition: qnumeric_p.h:62
The QScriptContext class represents a Qt Script function invocation.
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...
QScriptValue property(const QString &name, const ResolveFlags &mode=ResolvePrototype) const
Returns the value of this QScriptValue&#39;s property with the given name, using the given mode to resolv...
bool isFunction() const
Returns true if this QScriptValue is a function; otherwise returns false.
QScriptValue throwError(Error error, const QString &text)
Throws an error with the given text.
QScriptValue globalObject() const
Returns this engine&#39;s Global Object.
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
void popContext()
Pops the current execution context and restores the previous one.
The QString class provides a Unicode character string.
Definition: qstring.h:83
T * qobject_cast(QObject *object)
Definition: qobject.h:375
#define Q_D(Class)
Definition: qglobal.h:2482
static QChar separator()
Returns the native directory separator: "/" under Unix (including Mac OS X) and "\\" under Windows...
Definition: qdir.cpp:1831
static QObjectList staticInstances()
Returns a list of static plugin instances (root components) held by the plugin loader.
void setThisObject(const QScriptValue &thisObject)
Sets the `this&#39; object associated with this QScriptContext to be thisObject.
The QScriptEngine class provides an environment for evaluating Qt Script code.
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QString canonicalFilePath() const
Returns the canonical path including the file name, i.e.
Definition: qfileinfo.cpp:551
static QScriptValue __setupPackage__(QScriptContext *ctx, QScriptEngine *eng)
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
The QCoreApplication class provides an event loop for console Qt applications.
void setProperty(const QString &name, const QScriptValue &value, const PropertyFlags &flags=KeepExistingFlags)
Sets the value of this QScriptValue&#39;s property with the given name to the given value.
QString & append(QChar c)
Definition: qstring.cpp:1777
virtual QStringList keys() const =0
The QFile class provides an interface for reading from and writing to files.
Definition: qfile.h:65
The QTextStream class provides a convenient interface for reading and writing text.
Definition: qtextstream.h:73
static QCoreApplication * instance()
Returns a pointer to the application&#39;s QCoreApplication (or QApplication) instance.
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
static QStringList libraryPaths()
Returns a list of paths that the application will search when dynamically loading libraries...
#define ctx
Definition: qgl.cpp:6094
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
QScriptContext * currentContext() const
Returns the current context.
virtual void initialize(const QString &key, QScriptEngine *engine)=0
QScriptContext * pushContext()
Enters a new execution context and returns the associated QScriptContext object.
QStringList split(const QString &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const Q_REQUIRED_RESULT
Splits the string into substrings wherever sep occurs, and returns the list of those strings...
Definition: qstring.cpp:6526
QScriptValue activationObject() const
Returns the activation object of this QScriptContext.
QScriptValue undefinedValue()
Returns a QScriptValue of the primitive type Undefined.
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
bool hasUncaughtException() const
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false...
static qreal dot(const QPointF &a, const QPointF &b)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
QScriptValue call(const QScriptValue &thisObject=QScriptValue(), const QScriptValueList &args=QScriptValueList())
Calls this QScriptValue as a function, using thisObject as the `this&#39; object in the function call...
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
QScriptValue uncaughtException() const
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception...
The QPluginLoader class loads a plugin at run-time.
Definition: qpluginloader.h:62

◆ installTranslatorFunctions()

void QScriptEngine::installTranslatorFunctions ( const QScriptValue object = QScriptValue())

Installs translator functions on the given object, or on the Global Object if no object is specified.

Since
4.5

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()
See also
{Internationalization with Qt}

Definition at line 3536 of file qscriptengine.cpp.

Referenced by QDeclarativeScriptEngine::QDeclarativeScriptEngine().

3537 {
3538  Q_D(QScriptEngine);
3539  QScript::APIShim shim(d);
3540  JSC::ExecState* exec = d->currentFrame;
3541  JSC::JSValue jscObject = d->scriptValueToJSCValue(object);
3542  JSC::JSGlobalObject *glob = d->originalGlobalObject();
3543  if (!jscObject || !jscObject.isObject())
3544  jscObject = d->globalObject();
3545 // unsigned attribs = JSC::DontEnum;
3546 
3547 #ifndef QT_NO_TRANSLATION
3548  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 5, JSC::Identifier(exec, "qsTranslate"), QScript::functionQsTranslate));
3549  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 2, JSC::Identifier(exec, "QT_TRANSLATE_NOOP"), QScript::functionQsTranslateNoOp));
3550  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 3, JSC::Identifier(exec, "qsTr"), QScript::functionQsTr));
3551  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "QT_TR_NOOP"), QScript::functionQsTrNoOp));
3552  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "qsTrId"), QScript::functionQsTrId));
3553  JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "QT_TRID_NOOP"), QScript::functionQsTrIdNoOp));
3554 #endif
3555 
3556  glob->stringPrototype()->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "arg"), QScript::stringProtoFuncArg));
3557 }
double d
Definition: qnumeric_p.h:62
static JSC::JSValue JSC_HOST_CALL functionQsTranslateNoOp(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
static JSC::JSValue JSC_HOST_CALL functionQsTrIdNoOp(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
static JSC::JSValue JSC_HOST_CALL functionQsTrId(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
static JSC::JSValue JSC_HOST_CALL functionQsTranslate(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
#define Q_D(Class)
Definition: qglobal.h:2482
static JSC::JSValue JSC_HOST_CALL functionQsTr(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
static JSC::JSValue JSC_HOST_CALL stringProtoFuncArg(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)
The QScriptEngine class provides an environment for evaluating Qt Script code.
static JSC::JSValue JSC_HOST_CALL functionQsTrNoOp(JSC::ExecState *, JSC::JSObject *, JSC::JSValue, const JSC::ArgList &)

◆ isEvaluating()

bool QScriptEngine::isEvaluating ( ) const

Returns true if this engine is currently evaluating a script, otherwise returns false.

Since
4.4
See also
evaluate(), abortEvaluation()

Definition at line 4191 of file qscriptengine.cpp.

Referenced by abortEvaluation(), and QScriptDebuggerCommandExecutor::execute().

4192 {
4193  Q_D(const QScriptEngine);
4194  return (d->currentFrame != d->globalExec()) || d->inEval;
4195 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newActivationObject()

QScriptValue QScriptEngine::newActivationObject ( )
Warning
This function is not part of the public interface.

Definition at line 2339 of file qscriptengine.cpp.

2340 {
2341  qWarning("QScriptEngine::newActivationObject() not implemented");
2342  // ### JSActivation or JSVariableObject?
2343  return QScriptValue();
2344 }
Q_CORE_EXPORT void qWarning(const char *,...)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ newArray()

QScriptValue QScriptEngine::newArray ( uint  length = 0)

Creates a QtScript object of class Array with the given length.

See also
newObject()

Definition at line 2426 of file qscriptengine.cpp.

Referenced by QDeclarativeInclude::callback(), QDeclarativeEnginePrivate::createQmlObject(), messageToScriptValue(), QDeclarativeWorkerScriptEnginePrivate::processMessage(), QDeclarativeObjectMethodScriptClass::property(), qDBusReplyToScriptValue(), qScriptValueFromSequence(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().

2427 {
2428  Q_D(QScriptEngine);
2429  QScript::APIShim shim(d);
2430  return d->scriptValueFromJSCValue(d->newArray(d->currentFrame, length));
2431 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newDate() [1/2]

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

2453 {
2454  Q_D(QScriptEngine);
2455  QScript::APIShim shim(d);
2456  return d->scriptValueFromJSCValue(d->newDate(d->currentFrame, value));
2457 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newDate() [2/2]

QScriptValue QScriptEngine::newDate ( const QDateTime value)

Creates a QtScript object of class Date from the given value.

See also
QScriptValue::toDateTime()

Definition at line 2464 of file qscriptengine.cpp.

2465 {
2466  Q_D(QScriptEngine);
2467  QScript::APIShim shim(d);
2468  return d->scriptValueFromJSCValue(d->newDate(d->currentFrame, value));
2469 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newFunction() [1/3]

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:

static QScriptValue getSetFoo(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue callee = context->callee();
if (context->argumentCount() == 1) // writing?
callee.setProperty("value", context->argument(0));
return callee.property("value");
}
....
QScriptValue object = engine.newObject();
object.setProperty("foo", engine.newFunction(getSetFoo),

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.:

QScriptValue object = engine.newObject();
object.setProperty("foo", engine.newFunction(getFoo), QScriptValue::PropertyGetter);
object.setProperty("foo", engine.newFunction(setFoo), QScriptValue::PropertySetter);
See also
QScriptValue::call()

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

2390 {
2391  Q_D(QScriptEngine);
2392  QScript::APIShim shim(d);
2393  JSC::ExecState* exec = d->currentFrame;
2394  JSC::JSValue function = new (exec)QScript::FunctionWrapper(exec, length, JSC::Identifier(exec, ""), fun);
2395  QScriptValue result = d->scriptValueFromJSCValue(function);
2396  QScriptValue proto = newObject();
2397  result.setProperty(QLatin1String("prototype"), proto,
2399  proto.setProperty(QLatin1String("constructor"), result, QScriptValue::SkipInEnumeration);
2400  return result;
2401 }
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
QScriptValue newObject()
Creates a QtScript object of class Object.
void setProperty(const QString &name, const QScriptValue &value, const PropertyFlags &flags=KeepExistingFlags)
Sets the value of this QScriptValue&#39;s property with the given name to the given value.
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ newFunction() [2/3]

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:

{
if (context->calledAsConstructor()) {
// initialize the new object
context->thisObject().setProperty("bar", ...);
// ...
// return a non-object value to indicate that the
// thisObject() should be the result of the "new Foo()" expression
return engine->undefinedValue();
} else {
// not called as "new Foo()", just "Foo()"
// create our own object and return that one
QScriptValue object = engine->newObject();
object.setPrototype(context->callee().property("prototype"));
object.setProperty("baz", ...);
return object;
}
}
...
QScriptValue fooProto = engine->newObject();
fooProto.setProperty("whatever", ...);
engine->globalObject().setProperty("Foo", engine->newFunction(Foo, fooProto));

To wrap a custom type and provide a constructor for it, you'd typically do something like this:

class Bar { ... };
QScriptValue constructBar(QScriptContext *context, QScriptEngine *engine)
{
Bar bar;
// initialize from arguments in context, if desired
...
return engine->toScriptValue(bar);
}
class BarPrototype : public QObject, public QScriptable
{
// provide the scriptable interface of this type using slots and properties
...
};
...
// create and register the Bar prototype and constructor in the engine
BarPrototype *barPrototypeObject = new BarPrototype(...);
QScriptValue barProto = engine->newQObject(barPrototypeObject);
engine->setDefaultPrototype(qMetaTypeId<Bar>, barProto);
QScriptValue barCtor = engine->newFunction(constructBar, barProto);
engine->globalObject().setProperty("Bar", barCtor);

Definition at line 2110 of file qscriptengine.cpp.

2113 {
2114  Q_D(QScriptEngine);
2115  QScript::APIShim shim(d);
2116  JSC::ExecState* exec = d->currentFrame;
2117  JSC::JSValue function = new (exec)QScript::FunctionWrapper(exec, length, JSC::Identifier(exec, ""), fun);
2118  QScriptValue result = d->scriptValueFromJSCValue(function);
2119  result.setProperty(QLatin1String("prototype"), prototype,
2121  const_cast<QScriptValue&>(prototype)
2122  .setProperty(QLatin1String("constructor"), result, QScriptValue::SkipInEnumeration);
2123  return result;
2124 }
double d
Definition: qnumeric_p.h:62
bool setProperty(const char *name, const QVariant &value)
Sets the value of the object&#39;s name property to value.
Definition: qobject.cpp:3755
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
static QByteArray prototype(const QList< QByteArray > &parameterTypes, const QList< QByteArray > &parameterNames, bool *ok)
Definition: qaxserver.cpp:685
void setProperty(const QString &name, const QScriptValue &value, const PropertyFlags &flags=KeepExistingFlags)
Sets the value of this QScriptValue&#39;s property with the given name to the given value.
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ newFunction() [3/3]

QScriptValue QScriptEngine::newFunction ( QScriptEngine::FunctionWithArgSignature  fun,
void *  arg 
)
Warning
This function is not part of the public interface.
Since
4.4

Definition at line 2407 of file qscriptengine.cpp.

2408 {
2409  Q_D(QScriptEngine);
2410  QScript::APIShim shim(d);
2411  JSC::ExecState* exec = d->currentFrame;
2412  JSC::JSValue function = new (exec)QScript::FunctionWithArgWrapper(exec, /*length=*/0, JSC::Identifier(exec, ""), fun, arg);
2413  QScriptValue result = d->scriptValueFromJSCValue(function);
2414  QScriptValue proto = newObject();
2415  result.setProperty(QLatin1String("prototype"), proto,
2417  proto.setProperty(QLatin1String("constructor"), result, QScriptValue::SkipInEnumeration);
2418  return result;
2419 }
double d
Definition: qnumeric_p.h:62
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
QScriptValue newObject()
Creates a QtScript object of class Object.
void setProperty(const QString &name, const QScriptValue &value, const PropertyFlags &flags=KeepExistingFlags)
Sets the value of this QScriptValue&#39;s property with the given name to the given value.
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ newObject() [1/2]

QScriptValue QScriptEngine::newObject ( )

Creates a QtScript object of class Object.

The prototype of the created object will be the Object prototype object.

See also
newArray(), QScriptValue::setProperty()

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

2297 {
2298  Q_D(QScriptEngine);
2299  QScript::APIShim shim(d);
2300  return d->scriptValueFromJSCValue(d->newObject());
2301 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newObject() [2/2]

QScriptValue QScriptEngine::newObject ( QScriptClass scriptClass,
const QScriptValue data = QScriptValue() 
)

Creates a QtScript Object of the given class, scriptClass.

Since
4.4 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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

See also
QScriptValue::scriptClass(), reportAdditionalMemoryCost()

Definition at line 2320 of file qscriptengine.cpp.

2322 {
2323  Q_D(QScriptEngine);
2324  QScript::APIShim shim(d);
2325  JSC::ExecState* exec = d->currentFrame;
2326  QScriptObject *result = new (exec) QScriptObject(d->scriptObjectStructure);
2327  result->setDelegate(new QScript::ClassObjectDelegate(scriptClass));
2328  QScriptValue scriptObject = d->scriptValueFromJSCValue(result);
2329  scriptObject.setData(data);
2330  QScriptValue proto = scriptClass->prototype();
2331  if (proto.isValid())
2332  scriptObject.setPrototype(proto);
2333  return scriptObject;
2334 }
double d
Definition: qnumeric_p.h:62
virtual QScriptValue prototype() const
Returns the object to be used as the prototype of new instances of this class (created with QScriptEn...
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
void setPrototype(const QScriptValue &prototype)
If this QScriptValue is an object, sets the internal prototype (__proto__ property) of this object to...
void setDelegate(QScriptObjectDelegate *delegate)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57
bool isValid() const
Returns true if this QScriptValue is valid; otherwise returns false.
void setData(const QScriptValue &data)
Sets the internal data of this QScriptValue object.

◆ newQMetaObject()

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:

QScriptValue mySpecialQObjectConstructor(QScriptContext *context,
QScriptEngine *engine)
{
QObject *parent = context->argument(0).toQObject();
QObject *object = new QObject(parent);
return engine->newQObject(object, QScriptEngine::ScriptOwnership);
}
...
QScriptValue ctor = engine.newFunction(mySpecialQObjectConstructor);
engine.globalObject().setProperty("QObject", metaObject);
QScriptValue result = engine.evaluate("new QObject()");
See also
newQObject(), scriptValueFromQMetaObject()

Definition at line 2487 of file qscriptengine.cpp.

Referenced by QDBusConnectionConstructor::QDBusConnectionConstructor(), QDeclarativeScriptEngine::QDeclarativeScriptEngine(), QScriptDBusInterfaceConstructor::QScriptDBusInterfaceConstructor(), and QScriptDBusMessageConstructor::QScriptDBusMessageConstructor().

2489 {
2490  Q_D(QScriptEngine);
2491  QScript::APIShim shim(d);
2492  JSC::JSValue jscCtor = d->scriptValueToJSCValue(ctor);
2493  JSC::JSValue jscQMetaObject = d->newQMetaObject(metaObject, jscCtor);
2494  return d->scriptValueFromJSCValue(jscQMetaObject);
2495 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newQObject() [1/2]

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.

See also
QScriptValue::toQObject(), reportAdditionalMemoryCost()

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

2223 {
2224  Q_D(QScriptEngine);
2225  QScript::APIShim shim(d);
2226  JSC::JSValue jscQObject = d->newQObject(object, ownership, options);
2227  return d->scriptValueFromJSCValue(jscQObject);
2228 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newQObject() [2/2]

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.

Since
4.4 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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.

See also
reportAdditionalMemoryCost()

Definition at line 2260 of file qscriptengine.cpp.

2264 {
2265  Q_D(QScriptEngine);
2266  if (!scriptObject.isObject())
2267  return newQObject(qtObject, ownership, options);
2268  QScript::APIShim shim(d);
2269  JSC::JSObject *jscObject = JSC::asObject(QScriptValuePrivate::get(scriptObject)->jscValue);
2270  if (!jscObject->inherits(&QScriptObject::info)) {
2271  qWarning("QScriptEngine::newQObject(): changing class of non-QScriptObject not supported");
2272  return QScriptValue();
2273  }
2274  QScriptObject *jscScriptObject = static_cast<QScriptObject*>(jscObject);
2275  if (!scriptObject.isQObject()) {
2276  jscScriptObject->setDelegate(new QScript::QObjectDelegate(qtObject, ownership, options));
2277  } else {
2278  QScript::QObjectDelegate *delegate = static_cast<QScript::QObjectDelegate*>(jscScriptObject->delegate());
2279  delegate->setValue(qtObject);
2280  delegate->setOwnership(ownership);
2281  delegate->setOptions(options);
2282  }
2283  return scriptObject;
2284 }
double d
Definition: qnumeric_p.h:62
static QScriptValuePrivate * get(const QScriptValue &q)
QScriptObjectDelegate * delegate() const
static const JSC::ClassInfo info
#define Q_D(Class)
Definition: qglobal.h:2482
void setOwnership(QScriptEngine::ValueOwnership ownership)
The QScriptEngine class provides an environment for evaluating Qt Script code.
void setValue(QObject *value)
Q_CORE_EXPORT void qWarning(const char *,...)
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.
bool isQObject() const
Returns true if this QScriptValue is a QObject; otherwise returns false.
void setDelegate(QScriptObjectDelegate *delegate)
void setOptions(QScriptEngine::QObjectWrapOptions options)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57
bool isObject() const
Returns true if this QScriptValue is of the Object type; otherwise returns false. ...

◆ newRegExp() [1/2]

QScriptValue QScriptEngine::newRegExp ( const QRegExp regexp)

Creates a QtScript object of class RegExp with the given regexp.

See also
QScriptValue::toRegExp()

Definition at line 2134 of file qscriptengine.cpp.

Referenced by QScriptEnginePrivate::create(), and QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue().

2135 {
2136  Q_D(QScriptEngine);
2137  QScript::APIShim shim(d);
2138  return d->scriptValueFromJSCValue(d->newRegExp(d->currentFrame, regexp));
2139 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newRegExp() [2/2]

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.

2441 {
2442  Q_D(QScriptEngine);
2443  QScript::APIShim shim(d);
2444  return d->scriptValueFromJSCValue(d->newRegExp(d->currentFrame, pattern, flags));
2445 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newVariant() [1/2]

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.

See also
setDefaultPrototype(), QScriptValue::toVariant(), reportAdditionalMemoryCost()

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

2154 {
2155  Q_D(QScriptEngine);
2156  QScript::APIShim shim(d);
2157  return d->scriptValueFromJSCValue(d->newVariant(value));
2158 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ newVariant() [2/2]

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.

Since
4.4 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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.

See also
reportAdditionalMemoryCost()

Definition at line 2189 of file qscriptengine.cpp.

2191 {
2192  Q_D(QScriptEngine);
2193  QScript::APIShim shim(d);
2194  JSC::JSValue jsObject = d->scriptValueToJSCValue(object);
2195  return d->scriptValueFromJSCValue(d->newVariant(jsObject, value));
2196 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ nullValue()

QScriptValue QScriptEngine::nullValue ( )

◆ objectById()

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.

Warning
This function is not part of the public interface.
See also
QScriptValue::objectId()

Definition at line 4424 of file qscriptengine.cpp.

Referenced by QJSDebuggerAgent::expandObjectById(), QJSDebuggerAgent::setProperty(), and QScriptDebuggerValue::toScriptValue().

4425 {
4426  Q_D(const QScriptEngine);
4427  // Assumes that the cell was not been garbage collected
4428  return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue((JSC::JSCell*)id);
4429 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ popContext()

void QScriptEngine::popContext ( )

Pops the current execution context and restores the previous one.

This function must be used in conjunction with pushContext().

See also
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().

2851 {
2852  if (agent())
2853  agent()->contextPop();
2854  Q_D(QScriptEngine);
2855  QScript::APIShim shim(d);
2856  if (d->currentFrame->returnPC() != 0 || d->currentFrame->codeBlock() != 0
2857  || !currentContext()->parentContext()) {
2858  qWarning("QScriptEngine::popContext() doesn't match with pushContext()");
2859  return;
2860  }
2861 
2862  d->popContext();
2863 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
Q_CORE_EXPORT void qWarning(const char *,...)
virtual void contextPop()
This function is called when the current script context is about to be popped.
QScriptContext * currentContext() const
Returns the current context.
QScriptEngineAgent * agent() const
Returns the agent currently installed on this engine, or 0 if no agent is installed.
QScriptContext * parentContext() const
Returns the parent context of this QScriptContext.

◆ processEventsInterval()

int QScriptEngine::processEventsInterval ( ) const

Returns the interval in milliseconds between calls to QCoreApplication::processEvents() while the interpreter is running.

See also
setProcessEventsInterval()

Definition at line 4174 of file qscriptengine.cpp.

4175 {
4176  Q_D(const QScriptEngine);
4177  return d->processEventsInterval;
4178 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ pushContext()

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:

QScriptContext *context = engine.pushContext();
context->activationObject().setProperty("myArg", 123);
engine.evaluate("var tmp = myArg + 42");
...

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

See also
popContext()

Definition at line 2751 of file qscriptengine.cpp.

Referenced by QScriptDebuggerBackend::doPendingEvaluate(), and importExtension().

2752 {
2753  Q_D(QScriptEngine);
2754  QScript::APIShim shim(d);
2755 
2756  JSC::CallFrame* newFrame = d->pushContext(d->currentFrame, d->currentFrame->globalData().dynamicGlobalObject,
2757  JSC::ArgList(), /*callee = */0);
2758 
2759  if (agent())
2760  agent()->contextPush();
2761 
2762  return d->contextForFrame(newFrame);
2763 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
QScriptEngineAgent * agent() const
Returns the agent currently installed on this engine, or 0 if no agent is installed.
virtual void contextPush()
This function is called when a new script context has been pushed.
ExecState CallFrame

◆ registerCustomType()

void QScriptEngine::registerCustomType ( int  type,
MarshalFunction  mf,
DemarshalFunction  df,
const QScriptValue prototype 
)
private
Warning
This function is not part of the public interface.

Definition at line 3496 of file qscriptengine.cpp.

Referenced by qScriptRegisterMetaType_helper().

3499 {
3500  Q_D(QScriptEngine);
3501  QScript::APIShim shim(d);
3502  QScriptTypeInfo *info = d->m_typeInfos.value(type);
3503  if (!info) {
3504  info = new QScriptTypeInfo();
3505  d->m_typeInfos.insert(type, info);
3506  }
3507  info->marshal = mf;
3508  info->demarshal = df;
3509  info->prototype = d->scriptValueToJSCValue(prototype);
3510 }
double d
Definition: qnumeric_p.h:62
int type
Definition: qmetatype.cpp:239
static mach_timebase_info_data_t info
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
JSC::JSValue prototype
QScriptEngine::DemarshalFunction demarshal
QScriptEngine::MarshalFunction marshal

◆ reportAdditionalMemoryCost()

void QScriptEngine::reportAdditionalMemoryCost ( int  size)

Reports an additional memory cost of the given size, measured in bytes, to the garbage collector.

Since
4.7

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.

See also
collectGarbage()

Definition at line 4127 of file qscriptengine.cpp.

4128 {
4129  Q_D(QScriptEngine);
4130  d->reportAdditionalMemoryCost(size);
4131 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ scriptValueFromQMetaObject()

template<class T >
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:

...
QScriptValue lineEditClass = engine.scriptValueFromQMetaObject<QLineEdit>();
engine.globalObject().setProperty("QLineEdit", lineEditClass);
See also
QScriptEngine::newQMetaObject()

Definition at line 295 of file qscriptengine.h.

296 {
297  typedef QScriptValue(*ConstructPtr)(QScriptContext *, QScriptEngine *, T *);
298  ConstructPtr cptr = qscriptQMetaObjectConstructor<T>;
299  return newQMetaObject(&T::staticMetaObject,
300  newFunction(reinterpret_cast<FunctionWithArgSignature>(cptr), 0));
301 }
QScriptValue newFunction(FunctionSignature signature, int length=0)
Creates a QScriptValue that wraps a native (C++) function.
The QScriptContext class represents a Qt Script function invocation.
The QScriptEngine class provides an environment for evaluating Qt Script code.
QScriptValue newQMetaObject(const QMetaObject *metaObject, const QScriptValue &ctor=QScriptValue())
Creates a QtScript object that represents a QObject class, using the the given metaObject and constru...
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ setAgent()

void QScriptEngine::setAgent ( QScriptEngineAgent agent)

Installs the given agent on this engine.

Since
4.4

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.

See also
agent()

Definition at line 4325 of file qscriptengine.cpp.

Referenced by QScriptDebuggerBackend::attachTo(), QScriptDebuggerBackend::detach(), QJSDebuggerAgent::QJSDebuggerAgent(), and QJSDebuggerAgent::~QJSDebuggerAgent().

4326 {
4327  Q_D(QScriptEngine);
4328  if (agent && (agent->engine() != this)) {
4329  qWarning("QScriptEngine::setAgent(): "
4330  "cannot set agent belonging to different engine");
4331  return;
4332  }
4333  QScript::APIShim shim(d);
4334  if (d->activeAgent)
4335  QScriptEngineAgentPrivate::get(d->activeAgent)->detach();
4336  d->activeAgent = agent;
4337  if (agent) {
4338  QScriptEngineAgentPrivate::get(agent)->attach();
4339  }
4340 }
double d
Definition: qnumeric_p.h:62
QScriptEngine * engine() const
Returns the QScriptEngine that this agent is associated with.
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
Q_CORE_EXPORT void qWarning(const char *,...)
static QScriptEngineAgent * get(QScriptEngineAgentPrivate *p)
QScriptEngineAgent * agent() const
Returns the agent currently installed on this engine, or 0 if no agent is installed.

◆ setDefaultPrototype()

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

See also
defaultPrototype(), qScriptRegisterMetaType(), QScriptable, {Default Prototypes Example}

Definition at line 3010 of file qscriptengine.cpp.

Referenced by QScriptDBusMessageConstructor::QScriptDBusMessageConstructor().

3011 {
3012  Q_D(QScriptEngine);
3013  d->setDefaultPrototype(metaTypeId, d->scriptValueToJSCValue(prototype));
3014 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ setGlobalObject()

void QScriptEngine::setGlobalObject ( const QScriptValue object)

Sets this engine's Global Object to be the given object.

Since
4.5

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

2054 {
2055  Q_D(QScriptEngine);
2056  if (!object.isObject())
2057  return;
2058  QScript::APIShim shim(d);
2059  JSC::JSObject *jscObject = JSC::asObject(d->scriptValueToJSCValue(object));
2060  d->setGlobalObject(jscObject);
2061 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ setProcessEventsInterval()

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.

See also
processEventsInterval()

Definition at line 4156 of file qscriptengine.cpp.

4157 {
4158  Q_D(QScriptEngine);
4159  d->processEventsInterval = interval;
4160 
4161  if (interval > 0)
4162  d->globalData->timeoutChecker->setCheckInterval(interval);
4163 
4164  d->timeoutChecker()->setShouldProcessEvents(interval > 0);
4165 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ signalHandlerException

void QScriptEngine::signalHandlerException ( const QScriptValue exception)
signal

This signal is emitted when a script function connected to a signal causes an exception.

Since
4.4
See also
qScriptConnect()

◆ toObject()

QScriptValue QScriptEngine::toObject ( const QScriptValue value)

Converts the given value to an object, if such a conversion is possible; otherwise returns an invalid QScriptValue.

Since
4.5

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).
See also
newObject()

Definition at line 4401 of file qscriptengine.cpp.

Referenced by abortEvaluation(), and QScriptValue::toObject().

4402 {
4403  Q_D(QScriptEngine);
4404  QScript::APIShim shim(d);
4405  JSC::JSValue jscValue = d->scriptValueToJSCValue(value);
4406  if (!jscValue || jscValue.isUndefined() || jscValue.isNull())
4407  return QScriptValue();
4408  JSC::ExecState* exec = d->currentFrame;
4409  JSC::JSValue result = jscValue.toObject(exec);
4410  return d->scriptValueFromJSCValue(result);
4411 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ toScriptValue()

template<typename T >
QScriptValue QScriptEngine::toScriptValue ( const T &  value)
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().

See also
fromScriptValue(), 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().

214  {
215  return qScriptValueFromValue(this, value);
216  }
QScriptValue qScriptValueFromValue(QScriptEngine *engine, const T &value)

◆ toStringHandle()

QScriptString QScriptEngine::toStringHandle ( const QString str)

Returns a handle that represents the given string, str.

Since
4.4

QScriptString can be used to quickly look up properties, and compare property names, of script objects.

See also
QScriptValue::property()

Definition at line 4372 of file qscriptengine.cpp.

Referenced by QDeclarativeSqlQueryScriptClass::QDeclarativeSqlQueryScriptClass().

4373 {
4374  Q_D(QScriptEngine);
4375  QScript::APIShim shim(d);
4376  return d->toStringHandle(JSC::Identifier(d->currentFrame, str));
4377 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

◆ uncaughtException()

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.

See also
hasUncaughtException(), uncaughtExceptionLineNumber(),

Definition at line 2910 of file qscriptengine.cpp.

Referenced by QDeclarativeExpressionPrivate::exceptionToError(), QDeclarativeInclude::finished(), importExtension(), QDeclarativeInclude::include(), uncaughtExceptionBacktrace(), uncaughtExceptionLineNumber(), and QDeclarativeInclude::worker_include().

2911 {
2912  Q_D(const QScriptEngine);
2913  QScriptValue result;
2914  JSC::ExecState* exec = d->globalExec();
2915  if (exec->hadException())
2916  result = const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(exec->exception());
2917  else
2918  result = d->currentException();
2919  return result;
2920 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ uncaughtExceptionBacktrace()

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

See also
uncaughtException()

Definition at line 2944 of file qscriptengine.cpp.

2945 {
2946  if (!hasUncaughtException())
2947  return QStringList();
2948 // ### currently no way to get a full backtrace from JSC without installing a
2949 // debugger that reimplements exception() and store the backtrace there.
2950  QScriptValue value = uncaughtException();
2951  if (!value.isError())
2952  return QStringList();
2953  QStringList result;
2954  result.append(QString::fromLatin1("<anonymous>()@%0:%1")
2955  .arg(value.property(QLatin1String("fileName")).toString())
2956  .arg(value.property(QLatin1String("lineNumber")).toInt32()));
2957  return result;
2958 }
QScriptValue property(const QString &name, const ResolveFlags &mode=ResolvePrototype) const
Returns the value of this QScriptValue&#39;s property with the given name, using the given mode to resolv...
qint32 toInt32() const
Returns the signed 32-bit integer value of this QScriptValue, using the conversion rules described in...
bool isError() const
Returns true if this QScriptValue is an object of the Error class; otherwise returns false...
QString toString() const
Returns the string value of this QScriptValue, as defined in ECMA-262 section 9.8, "ToString".
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
bool hasUncaughtException() const
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false...
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57
QScriptValue uncaughtException() const
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception...

◆ uncaughtExceptionLineNumber()

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

See also
hasUncaughtException()

Definition at line 2930 of file qscriptengine.cpp.

Referenced by QDeclarativeExpressionPrivate::exceptionToError(), and QScriptDebuggerScriptedConsoleCommand::parse().

2931 {
2932  if (!hasUncaughtException())
2933  return -1;
2934  return uncaughtException().property(QLatin1String("lineNumber")).toInt32();
2935 }
QScriptValue property(const QString &name, const ResolveFlags &mode=ResolvePrototype) const
Returns the value of this QScriptValue&#39;s property with the given name, using the given mode to resolv...
qint32 toInt32() const
Returns the signed 32-bit integer value of this QScriptValue, using the conversion rules described in...
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
bool hasUncaughtException() const
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false...
QScriptValue uncaughtException() const
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception...

◆ undefinedValue()

QScriptValue QScriptEngine::undefinedValue ( )

Returns a QScriptValue of the primitive type Undefined.

See also
nullValue()

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

2080 {
2081  Q_D(QScriptEngine);
2082  return d->scriptValueFromJSCValue(JSC::jsUndefined());
2083 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QScriptEngine class provides an environment for evaluating Qt Script code.

Friends and Related Functions

◆ FunctionSignature()

FunctionSignature
related

The function signature QScriptValue f(QScriptContext *, QScriptEngine *).

A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.

◆ FunctionWithArgSignature()

FunctionWithArgSignature
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.

◆ qScriptConnect()

bool qScriptConnect ( QObject sender,
const char *  signal,
const QScriptValue receiver,
const QScriptValue function 
)
related

Creates a connection from the signal in the sender to the given function.

Since
4.4

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.

See also
qScriptDisconnect(), QScriptEngine::signalHandlerException()

Definition at line 4242 of file qscriptengine.cpp.

4244 {
4245  if (!sender || !signal)
4246  return false;
4247  if (!function.isFunction())
4248  return false;
4249  if (receiver.isObject() && (receiver.engine() != function.engine()))
4250  return false;
4251  QScriptEnginePrivate *engine = QScriptEnginePrivate::get(function.engine());
4252  QScript::APIShim shim(engine);
4253  JSC::JSValue jscReceiver = engine->scriptValueToJSCValue(receiver);
4254  JSC::JSValue jscFunction = engine->scriptValueToJSCValue(function);
4255  return engine->scriptConnect(sender, signal, jscReceiver, jscFunction,
4257 }
static QScriptEnginePrivate * get(QScriptEngine *q)
JSC::JSValue scriptValueToJSCValue(const QScriptValue &value)
QScriptEngine * engine() const
Returns the QScriptEngine that created this QScriptValue, or 0 if this QScriptValue is invalid or the...
bool isFunction(JSC::JSValue value)
bool isObject() const
Returns true if this QScriptValue is of the Object type; otherwise returns false. ...
bool scriptConnect(QObject *sender, const char *signal, JSC::JSValue receiver, JSC::JSValue function, Qt::ConnectionType type)

◆ qScriptDisconnect()

bool qScriptDisconnect ( QObject sender,
const char *  signal,
const QScriptValue receiver,
const QScriptValue function 
)
related

Disconnects the signal in the sender from the given (receiver, function) pair.

Since
4.4

Returns true if the connection is successfully broken; otherwise returns false.

See also
qScriptConnect()

Definition at line 4272 of file qscriptengine.cpp.

4274 {
4275  if (!sender || !signal)
4276  return false;
4277  if (!function.isFunction())
4278  return false;
4279  if (receiver.isObject() && (receiver.engine() != function.engine()))
4280  return false;
4281  QScriptEnginePrivate *engine = QScriptEnginePrivate::get(function.engine());
4282  QScript::APIShim shim(engine);
4283  JSC::JSValue jscReceiver = engine->scriptValueToJSCValue(receiver);
4284  JSC::JSValue jscFunction = engine->scriptValueToJSCValue(function);
4285  return engine->scriptDisconnect(sender, signal, jscReceiver, jscFunction);
4286 }
static QScriptEnginePrivate * get(QScriptEngine *q)
JSC::JSValue scriptValueToJSCValue(const QScriptValue &value)
QScriptEngine * engine() const
Returns the QScriptEngine that created this QScriptValue, or 0 if this QScriptValue is invalid or the...
bool isFunction(JSC::JSValue value)
bool scriptDisconnect(QObject *sender, const char *signal, JSC::JSValue receiver, JSC::JSValue function)
bool isObject() const
Returns true if this QScriptValue is of the Object type; otherwise returns false. ...

◆ qScriptRegisterMetaType()

int qScriptRegisterMetaType ( QScriptEngine engine,
QScriptValue(*)(QScriptEngine *, const T &t)  toScriptValue,
void(*)(const QScriptValue &, T &t)  fromScriptValue,
const QScriptValue prototype = QScriptValue() 
)
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:

struct MyStruct {
int x;
int y;
};

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:

QScriptValue toScriptValue(QScriptEngine *engine, const MyStruct &s)
{
QScriptValue obj = engine->newObject();
obj.setProperty("x", s.x);
obj.setProperty("y", s.y);
return obj;
}
void fromScriptValue(const QScriptValue &obj, MyStruct &s)
{
s.x = obj.property("x").toInt32();
s.y = obj.property("y").toInt32();
}

Now we can register MyStruct with the engine:

Working with MyStruct values is now easy:

MyStruct s = qscriptvalue_cast<MyStruct>(context->argument(0));
...
MyStruct s2;
s2.x = s.x + 10;
s2.y = s.y + 20;
QScriptValue v = engine->toScriptValue(s2);

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:

QScriptValue createMyStruct(QScriptContext *, QScriptEngine *engine)
{
MyStruct s;
s.x = 123;
s.y = 456;
return engine->toScriptValue(s);
}
...
QScriptValue ctor = engine.newFunction(createMyStruct);
engine.globalObject().setProperty("MyStruct", ctor);
See also
qScriptRegisterSequenceMetaType(), qRegisterMetaType()

Definition at line 380 of file qscriptengine.h.

389 {
390  const int id = qRegisterMetaType<T>(); // make sure it's registered
391 
393  eng, id, reinterpret_cast<QScriptEngine::MarshalFunction>(toScriptValue),
394  reinterpret_cast<QScriptEngine::DemarshalFunction>(fromScriptValue),
395  prototype);
396 
397  return id;
398 }
friend void qScriptRegisterMetaType_helper(QScriptEngine *, int, MarshalFunction, DemarshalFunction, const QScriptValue &)
QScriptValue toScriptValue(const T &value)
Creates a QScriptValue with the given value.
T fromScriptValue(const QScriptValue &value)
Returns the given value converted to the template type T.

◆ qScriptRegisterMetaType_helper

void qScriptRegisterMetaType_helper ( QScriptEngine eng,
int  type,
QScriptEngine::MarshalFunction  mf,
QScriptEngine::DemarshalFunction  df,
const QScriptValue prototype 
)
friend

Definition at line 371 of file qscriptengine.h.

375 {
376  eng->registerCustomType(type, mf, df, prototype);
377 }
int type
Definition: qmetatype.cpp:239
void registerCustomType(int type, MarshalFunction mf, DemarshalFunction df, const QScriptValue &prototype)

◆ qScriptRegisterSequenceMetaType()

int qScriptRegisterSequenceMetaType ( QScriptEngine engine,
const QScriptValue prototype = QScriptValue() 
)
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:

...
qScriptRegisterSequenceMetaType<QVector<int> >(engine);
...
QVector<int> v = qscriptvalue_cast<QVector<int> >(engine->evaluate("[5, 1, 3, 2]"));
qSort(v.begin(), v.end());
QScriptValue a = engine->toScriptValue(v);
qDebug() << a.toString(); // outputs "[1, 2, 3, 5]"
See also
qScriptRegisterMetaType()

Definition at line 424 of file qscriptengine.h.

431 {
432  return qScriptRegisterMetaType<T>(engine, qScriptValueFromSequence,
434 }
void qScriptValueToSequence(const QScriptValue &value, Container &container)
Copies the elements in the sequence specified by value to the given container of template type Contai...
QScriptValue qScriptValueFromSequence(QScriptEngine *engine, const Container &container)
static QByteArray prototype(const QList< QByteArray > &parameterTypes, const QList< QByteArray > &parameterNames, bool *ok)
Definition: qaxserver.cpp:685

◆ qscriptvalue_cast_helper

bool qscriptvalue_cast_helper ( const QScriptValue value,
int  type,
void *  ptr 
)
friend

Definition at line 338 of file qscriptengine.h.

339 {
340  return QScriptEngine::convertV2(value, type, ptr);
341 }
int type
Definition: qmetatype.cpp:239
const T * ptr(const T &t)
static bool convertV2(const QScriptValue &value, int type, void *ptr)

◆ qScriptValueFromQMetaObject()

QScriptValue qScriptValueFromQMetaObject ( QScriptEngine engine)
related
Since
4.3

Uses engine to create a QScriptValue that represents the Qt class T.

This function is equivalent to QScriptEngine::scriptValueFromQMetaObject().

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QScriptEngine::newQMetaObject()

Definition at line 305 of file qscriptengine.h.

311 {
312  return engine->scriptValueFromQMetaObject<T>();
313 }
QScriptValue scriptValueFromQMetaObject()
Creates a QScriptValue that represents the Qt class T.

◆ qScriptValueFromSequence()

QScriptValue qScriptValueFromSequence ( QScriptEngine engine,
const Container &  container 
)
related
Since
4.3

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.

See also
QScriptEngine::fromScriptValue()

Definition at line 401 of file qscriptengine.h.

402 {
403  QScriptValue a = eng->newArray();
404  typename Container::const_iterator begin = cont.begin();
405  typename Container::const_iterator end = cont.end();
406  typename Container::const_iterator it;
407  quint32 i;
408  for (it = begin, i = 0; it != end; ++it, ++i)
409  a.setProperty(i, eng->toScriptValue(*it));
410  return a;
411 }
#define it(className, varName)
long ASN1_INTEGER_get ASN1_INTEGER * a
void setProperty(const QString &name, const QScriptValue &value, const PropertyFlags &flags=KeepExistingFlags)
Sets the value of this QScriptValue&#39;s property with the given name to the given value.
unsigned int quint32
Definition: qglobal.h:938
static const KeyPair *const end
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ qScriptValueFromValue()

QScriptValue qScriptValueFromValue ( QScriptEngine engine,
const T &  value 
)
related
Since
4.3

Creates a QScriptValue using the given engine with the given value of template type T.

This function is equivalent to QScriptEngine::toScriptValue().

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QScriptEngine::toScriptValue(), qscriptvalue_cast()

Definition at line 327 of file qscriptengine.h.

Referenced by qscriptQMetaObjectConstructor().

328 {
329  return qScriptValueFromValue_helper(engine, qMetaTypeId<T>(), &t);
330 }
friend QScriptValue qScriptValueFromValue_helper(QScriptEngine *, int, const void *)

◆ qScriptValueFromValue_helper

QScriptValue qScriptValueFromValue_helper ( QScriptEngine engine,
int  type,
const void *  ptr 
)
friend

Definition at line 318 of file qscriptengine.h.

319 {
320  if (!engine)
321  return QScriptValue();
322 
323  return engine->create(type, ptr);
324 }
int type
Definition: qmetatype.cpp:239
const T * ptr(const T &t)
QScriptValue create(int type, const void *ptr)
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ qScriptValueToSequence()

void qScriptValueToSequence ( const QScriptValue value,
Container &  container 
)
related

Copies the elements in the sequence specified by value to the given container of template type Container.

Since
4.3

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.

See also
qscriptvalue_cast()

Definition at line 414 of file qscriptengine.h.

415 {
416  quint32 len = value.property(QLatin1String("length")).toUInt32();
417  for (quint32 i = 0; i < len; ++i) {
418  QScriptValue item = value.property(i);
419  cont.push_back(qscriptvalue_cast<typename Container::value_type>(item));
420  }
421 }
QScriptValue property(const QString &name, const ResolveFlags &mode=ResolvePrototype) const
Returns the value of this QScriptValue&#39;s property with the given name, using the given mode to resolv...
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
quint32 toUInt32() const
Returns the unsigned 32-bit integer value of this QScriptValue, using the conversion rules described ...
unsigned int quint32
Definition: qglobal.h:938
The QScriptValue class acts as a container for the Qt Script data types.
Definition: qscriptvalue.h:57

◆ qScriptValueToValue()

T qScriptValueToValue ( const QScriptValue value)
related

Returns the given value converted to the template type T.

Since
4.3

This function is equivalent to QScriptEngine::fromScriptValue().

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QScriptEngine::fromScriptValue()

Definition at line 365 of file qscriptengine.h.

366 {
367  return qscriptvalue_cast<T>(value);
368 }
T qscriptvalue_cast(const QScriptValue &)

The documentation for this class was generated from the following files: