|  | Home · All Classes · Main Classes · Grouped Classes · Modules · Functions |

# QScriptEngine Class Reference
[QtScript module]

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

     #include <QScriptEngine>

Inherits QObject.

This class was introduced in Qt 4.3.

- List of all members, including inherited members

### Public Types

- typedef FunctionSignature
- enum ValueOwnership { QtOwnership, ScriptOwnership }

### Public Functions

- QScriptEngine ()
- QScriptEngine ( QObject * parent )
- virtual ~QScriptEngine ()
- bool canEvaluate ( const QString & program ) const
- QScriptContext * currentContext () const
- QScriptValue defaultPrototype ( int metaTypeId ) const
- QScriptValue evaluate ( const QString & program )
- QScriptValue evaluate ( const QString & program, int lineNumber )
- T fromScriptValue ( const QScriptValue & value )
- QScriptValue globalObject () const
- bool hasUncaughtException () const
- QScriptValue importExtension ( const QString & extension )
- QScriptValue newArray ( uint length = 0 )
- QScriptValue newDate ( qsreal value )
- QScriptValue newDate ( const QDateTime & value )
- QScriptValue newFunction ( FunctionSignature fun, int length = 0 )
- QScriptValue newFunction ( FunctionSignature fun, const QScriptValue & prototype, int length = 0 )
- QScriptValue newObject ()
- QScriptValue newQMetaObject ( const QMetaObject * metaObject, const QScriptValue & ctor = QScriptValue() )
- QScriptValue newQObject ( QObject * object, ValueOwnership ownership = QtOwnership )
- QScriptValue newRegExp ( const QRegExp & regexp )
- QScriptValue newRegExp ( const QString & pattern, const QString & flags )
- QScriptValue newVariant ( const QVariant & value )
- QScriptValue nullValue ()
- QScriptValue scriptValueFromQMetaObject ()
- void setDefaultPrototype ( int metaTypeId, const QScriptValue & prototype )
- QScriptValue toScriptValue ( const T & value )
- int uncaughtExceptionLineNumber () const
- QScriptValue undefinedValue ()

- 29 public functions inherited from QObject

### Related Non-Members

- typedef FunctionSignature
- int qScriptRegisterMetaType ( QScriptEngine * engine, QScriptValue(* ) ( QScriptEngine *, const T & t ) toScriptValue, void(* ) ( const QScriptValue &, T & t ) fromScriptValue, const QScriptValue & prototype = QScriptValue() )
- int qScriptRegisterSequenceMetaType ( QScriptEngine * engine, const QScriptValue & prototype = QScriptValue() )
- QScriptValue qScriptValueFromQMetaObject ( QScriptEngine * engine )
- QScriptValue qScriptValueFromValue ( QScriptEngine * engine, const T & value )
- T qScriptValueToValue ( const QScriptValue & value )

### Macros

- Q_SCRIPT_DECLARE_QMETAOBJECT ( QMetaObject, ArgType )

### Additional Inherited Members

- 1 property inherited from QObject
- 1 public slot inherited from QObject
- 1 signal inherited from QObject
- 5 static public members inherited from QObject
- 7 protected functions inherited from QObject

## Detailed Description

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

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

Use evaluate() to evaluate script code.

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

Use newObject() to create a standard Qt Script object. Use newDate() to create a `Date` object, and newRegExp() to create a `RegExp` object. Use newQObject() to wrap a QObject (or subclass) pointer, and newQMetaObject() to wrap a QMetaObject. Use newVariant() to wrap a QVariant. Use newFunction() to wrap a native (C++) function.

When wrapping a QObject pointer with newQObject(), properties, children and signals and slots of the object will then become available to script code as properties of the created QScriptValue. No binding code is needed because it is done dynamically using the Qt meta object system. See the QtScript documentation for more information.

Typically, you set properties in the engine's Global Object to make your own extensions available to scripts; properties of the Global Object are accessible from any script code.

Here is an example of how to expose a number value through the Global Object:

     QScriptValue myNumber = QScriptValue(&myEngine, 123);
     myEngine.globalObject().setProperty("myNumber", myNumber);

     ...

     QScriptValue myNumberPlusOne = myEngine.evaluate("myNumber + 1");

In addition to exposing plain data, you can also write C++ functions that can be invoked from script code. Such functions must have the signature QScriptEngine::FunctionSignature. You may then pass the function as argument to newFunction(). Here is an example of a function that returns the sum of its first two arguments:

     QScriptValue myAdd(QScriptContext *context, QScriptEngine *engine)
     {
        QScriptValue a = context->argument(0);
        QScriptValue b = context->argument(1);
        return QScriptValue(engine, a.toNumber() + b.toNumber());
     }

To expose this function to script code, you can set it as a property of the Global Object:

     QScriptValue fun = myEngine.scriptValue(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:

     QSscriptValue result = myEngine.evaluate("myAdd(myNumber, 1)");

A different approach to writing and exposing (either generic or non-generic) native functions is by using a combination of newQObject() and QScriptable; see the documentation for QScriptable for details.

You can extend the C++ types recognized by QScriptEngine by calling qScriptRegisterMetaType() or qScriptRegisterSequenceMetaType().

See also QScriptValue and QScriptContext.

## Member Type Documentation

### typedef QScriptEngine::FunctionSignature

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

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

### enum QScriptEngine::ValueOwnership

This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().

Constant | Value | Description
--- | --- | ---
`QScriptEngine::QtOwnership` | `0` | The standard Qt ownership rules apply, i.e. the associated data will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in Object Trees and Object Ownership.)
`QScriptEngine::ScriptOwnership` | `1` | The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value).

## Member Function Documentation

### QScriptEngine::QScriptEngine ()

Constructs a QScriptEngine object.

The Global Object is initialized to have properties as described in ECMA-262, Section 15.1.

### QScriptEngine::QScriptEngine ( QObject * parent )

Constructs a QScriptEngine object with the given parent.

The Global Object is initialized to have properties as described in ECMA-262, Section 15.1.

### QScriptEngine::~QScriptEngine () `[virtual]`

Destroys this QScriptEngine.

### bool QScriptEngine::canEvaluate ( const QString & program ) const

Returns true if program can be evaluated (is syntactically complete); otherwise returns false.

See also evaluate().

### QScriptContext * QScriptEngine::currentContext () const

Returns the current context.

The current context is typically accessed to retrieve the arguments to native functions.

### 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() and newVariant().

### QScriptValue QScriptEngine::evaluate ( const QString & program )

Evaluates program and returns the result of the evaluation.

The script code will be evaluated in the current context.

See also canEvaluate() and hasUncaughtException().

### QScriptValue QScriptEngine::evaluate ( const QString & program, int lineNumber )

This is an overloaded member function, provided for convenience.

Evaluates program and returns the result of the evaluation.

The script code will be evaluated in the current context.

See also canEvaluate() and hasUncaughtException().

### T QScriptEngine::fromScriptValue ( const QScriptValue & value )

Returns the given value converted to the template type `T`.

Warning: This function is not available with MSVC 6. Use qScriptValueToValue() or qscriptvalue_cast() instead if you need to support that version of the compiler.

See also toScriptValue() and qScriptRegisterMetaType().

### QScriptValue QScriptEngine::globalObject () const

Returns this engine's Global Object.

The Global Object contains the built-in objects that are part of ECMA-262, such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code.

### bool QScriptEngine::hasUncaughtException () const

Returns true if the last invocation of evaluate() resulted in an uncaught exception; otherwise returns false.

See also uncaughtExceptionLineNumber().

### 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 occured; in that case, the return value is the value that was thrown by the exception (usually an `Error` object).

QScriptEngine ensures that a particular extension is only imported once; subsequent calls to importExtension() with the same extension name will do nothing and return undefinedValue().

See also QScriptExtensionPlugin.

### QScriptValue QScriptEngine::newArray ( uint length = 0 )

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

### QScriptValue QScriptEngine::newDate ( qsreal value )

Creates a QScriptValue object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC).

### QScriptValue QScriptEngine::newDate ( const QDateTime & value )

This is an overloaded member function, provided for convenience.

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

### QScriptValue QScriptEngine::newFunction ( 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.

See also QScriptValue::call().

### QScriptValue QScriptEngine::newFunction ( FunctionSignature fun, const QScriptValue & prototype, int length = 0 )

This is an overloaded member function, provided for convenience.

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.

### QScriptValue QScriptEngine::newObject ()

Creates a QScriptValue object of class Object.

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

### QScriptValue QScriptEngine::newQMetaObject ( const QMetaObject * metaObject, const QScriptValue & ctor = QScriptValue() )

Creates a QScriptValue that represents a QObject class, using the the given metaObject and constructor ctor.

Enums of metaObject are available as properties of the created QScriptValue. When the class is called as a function, ctor will be called to create a new instance of the class.

### QScriptValue QScriptEngine::newQObject ( QObject * object, ValueOwnership ownership = QtOwnership )

Returns a QScriptValue that wraps the given QObject object, using the given ownership.

Signals and slots, properties and children of object are available as properties of the created QScriptValue. For more information, see the QtScript documentation.

### QScriptValue QScriptEngine::newRegExp ( const QRegExp & regexp )

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

### QScriptValue QScriptEngine::newRegExp ( const QString & pattern, const QString & flags )

This is an overloaded member function, provided for convenience.

Creates a QScriptValue object of class RegExp with the given pattern and flags.

### QScriptValue QScriptEngine::newVariant ( const QVariant & value )

Returns a QScriptValue 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 QScriptEngine::nullValue ()

Returns a QScriptValue of the primitive type Null.

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

     Q_SCRIPT_DECLARE_QMETAOBJECT(QLineEdit, QWidget*)

     ...

     QScriptValue lineEditClass = engine.scriptValueFromQMetaObject<QLineEdit>();
     engine.globalObject().setProperty("QLineEdit", lineEditClass);

Warning: This function is not available with MSVC 6. Use qScriptValueFromQMetaObject() instead if you need to support that version of the compiler.

### void QScriptEngine::setDefaultPrototype ( int metaTypeId, const QScriptValue & prototype )

Sets the default prototype of the given metaTypeId to prototype.

See also defaultPrototype(), newVariant(), and qScriptRegisterMetaType().

### QScriptValue QScriptEngine::toScriptValue ( const T & value )

Creates a QScriptValue with the given value.

Warning: This function is not available with MSVC 6. Use qScriptValueFromValue() instead if you need to support that version of the compiler.

See also fromScriptValue() and qScriptRegisterMetaType().

### int QScriptEngine::uncaughtExceptionLineNumber () const

Returns the line number where the last uncaught exception occurred.

See also hasUncaughtException().

### QScriptValue QScriptEngine::undefinedValue ()

Returns a QScriptValue of the primitive type Undefined.

## Related Non-Members

### typedef QScriptEngine::FunctionSignature

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

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

### int qScriptRegisterMetaType ( QScriptEngine * engine, QScriptValue(* ) ( QScriptEngine *, const T & t ) toScriptValue, void(* ) ( const QScriptValue &, T & t ) fromScriptValue, const QScriptValue & prototype = QScriptValue() )

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

Returns the internal ID used by QMetaType.

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 make our engine able to handle our custom 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:

     Q_DECLARE_METATYPE(MyStruct)

Here are the `MyStruct` conversion functions:

     QScriptValue toScriptValue(QScriptEngine *engine, const MyStruct &s)
     {
       QScriptValue obj = engine->newObject();
       obj.setProperty("x", QScriptValue(engine, s.x));
       obj.setProperty("y", QScriptValue(engine, 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:

     qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue);

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

### int qScriptRegisterSequenceMetaType ( QScriptEngine * engine, const QScriptValue & prototype = QScriptValue() )

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

     Q_DECLARE_METATYPE(QVector<int>)

     ...

     qScriptRegisterSequenceMetaType<QVector<int> >(engine);

See also qScriptRegisterMetaType().

### QScriptValue qScriptValueFromQMetaObject ( QScriptEngine * engine )

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

This function is equivalent to QScriptEngine::scriptValueFromQMetaObject(). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

### QScriptValue qScriptValueFromValue ( QScriptEngine * engine, const T & value )

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

This function is equivalent to QScriptEngine::toScriptValue(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

See also qScriptValueToValue().

### T qScriptValueToValue ( const QScriptValue & value )

Returns the given value converted to the template type `T`.

This function is equivalent to QScriptEngine::fromScriptValue(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

See also qScriptValueFromValue().

## Macro Documentation

### Q_SCRIPT_DECLARE_QMETAOBJECT ( QMetaObject, ArgType )

Declares the given QMetaObject. Used in combination with QScriptEngine::scriptValueFromQMetaObject() to make enums and instantiation of QMetaObject available to script code. The constructor generated by this macro takes a single argument of type ArgType; typically the argument is the parent type of the new instance, in which case ArgType is `QWidget*` or `QObject*`.