
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQScriptEngine class provides an environment for evaluating Qt Script code.More...
| Header: | #include <QScriptEngine> |
| Since: | Qt 4.3 |
| Inherits: | QObject |
Note: All functions in this class arereentrant.
| typedef | FunctionSignature |
| typedef | FunctionWithArgSignature |
| enum | QObjectWrapOption { ExcludeChildObjects, ExcludeSuperClassMethods, ExcludeSuperClassProperties, ExcludeSuperClassContents, ..., SkipMethodsInEnumeration } |
| flags | QObjectWrapOptions |
| enum | ValueOwnership { QtOwnership, ScriptOwnership, AutoOwnership } |
| QScriptEngine() | |
| QScriptEngine(QObject * parent) | |
| virtual | ~QScriptEngine() |
| void | abortEvaluation(const QScriptValue & result = QScriptValue()) |
| QScriptEngineAgent * | agent() const |
| QStringList | availableExtensions() const |
| void | clearExceptions() |
| void | collectGarbage() |
| QScriptContext * | currentContext() const |
| QScriptValue | defaultPrototype(int metaTypeId) const |
| QScriptValue | evaluate(const QString & program, const QString & fileName = QString(), int lineNumber = 1) |
| QScriptValue | evaluate(const QScriptProgram & program) |
| T | fromScriptValue(const QScriptValue & value) |
| QScriptValue | globalObject() const |
| bool | hasUncaughtException() const |
| QScriptValue | importExtension(const QString & extension) |
| QStringList | importedExtensions() const |
| void | installTranslatorFunctions(const QScriptValue & object = QScriptValue()) |
| bool | isEvaluating() const |
| 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 | newObject(QScriptClass * scriptClass, const QScriptValue & data = QScriptValue()) |
| QScriptValue | newQMetaObject(const QMetaObject * metaObject, const QScriptValue & ctor = QScriptValue()) |
| QScriptValue | newQObject(QObject * object, ValueOwnership ownership = QtOwnership, const QObjectWrapOptions & options = 0) |
| QScriptValue | newQObject(const QScriptValue & scriptObject, QObject * qtObject, ValueOwnership ownership = QtOwnership, const QObjectWrapOptions & options = 0) |
| QScriptValue | newRegExp(const QRegExp & regexp) |
| QScriptValue | newRegExp(const QString & pattern, const QString & flags) |
| QScriptValue | newVariant(const QVariant & value) |
| QScriptValue | newVariant(const QScriptValue & object, const QVariant & value) |
| QScriptValue | nullValue() |
| void | popContext() |
| int | processEventsInterval() const |
| QScriptContext * | pushContext() |
| void | reportAdditionalMemoryCost(int size) |
| QScriptValue | scriptValueFromQMetaObject() |
| void | setAgent(QScriptEngineAgent * agent) |
| void | setDefaultPrototype(int metaTypeId, const QScriptValue & prototype) |
| void | setGlobalObject(const QScriptValue & object) |
| void | setProcessEventsInterval(int interval) |
| QScriptValue | toObject(const QScriptValue & value) |
| QScriptValue | toScriptValue(const T & value) |
| QScriptString | toStringHandle(const QString & str) |
| QScriptValue | uncaughtException() const |
| QStringList | uncaughtExceptionBacktrace() const |
| int | uncaughtExceptionLineNumber() const |
| QScriptValue | undefinedValue() |
| void | signalHandlerException(const QScriptValue & exception) |
| QScriptSyntaxCheckResult | checkSyntax(const QString & program) |
| typedef | FunctionSignature |
| typedef | FunctionWithArgSignature |
| bool | qScriptConnect(QObject * sender, const char * signal, const QScriptValue & receiver, const QScriptValue & function) |
| bool | qScriptDisconnect(QObject * sender, const char * signal, const QScriptValue & receiver, const QScriptValue & function) |
| 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 | qScriptValueFromSequence(QScriptEngine * engine, const Container & container) |
| void | qScriptValueToSequence(const QScriptValue & value, Container & container) |
| Q_SCRIPT_DECLARE_QMETAOBJECT( QMetaObject, ArgType) |
TheQScriptEngine class provides an environment for evaluating Qt Script code.
See theQtScript documentation for information about the Qt Script language, and how to get started with scripting your C++ application.
Useevaluate() to evaluate script code; this is the C++ equivalent of the built-in script functioneval().
QScriptEngine myEngine;QScriptValue three= myEngine.evaluate("1 + 2");
evaluate() returns aQScriptValue that holds the result of the evaluation. TheQScriptValue class provides functions for converting the result to various C++ types (e.g.QScriptValue::toString() andQScriptValue::toNumber()).
The following code snippet shows how a script function can be defined and then invoked from C++ usingQScriptValue::call():
QScriptValue fun= myEngine.evaluate("(function(a, b) { return a + b; })");QScriptValueList args;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 toevaluate():
QString fileName="helloworld.qs";QFile scriptFile(fileName);if (!scriptFile.open(QIODevice::ReadOnly))// handle errorQTextStream stream(&scriptFile);QString contents= stream.readAll();scriptFile.close();myEngine.evaluate(contents, fileName);
Here we pass the name of the file as the second argument toevaluate(). 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 anyuncaughtExceptionBacktrace() involving the script).
TheglobalObject() function returns theGlobal 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 thenewQObject() ornewObject() functions, or constructor functions created bynewFunction().
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 anError object). You can check whether the evaluation caused an exception by callinghasUncaughtException(). In that case, you can call toString() on the error object to obtain an error message. The current uncaught exception is also available throughuncaughtException(). CallingclearExceptions() 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();}
ThecheckSyntax() function can be used to determine whether code can be usefully passed toevaluate().
UsenewObject() to create a standard Qt Script object; this is the C++ equivalent of the script statementnew Object(). You can use the object-specific functionality inQScriptValue to manipulate the script object (e.g.QScriptValue::setProperty()). Similarly, usenewArray() to create a Qt Script array object. UsenewDate() to create aDate object, andnewRegExp() to create aRegExp object.
UsenewQObject() to wrap aQObject (or subclass) pointer.newQObject() returns a proxy script object; properties, children, and signals and slots of theQObject 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
UseqScriptConnect() to connect a C++ signal to a script function; this is the Qt Script equivalent ofQObject::connect(). When a script function is invoked in response to a C++ signal, it can cause a script exception; you can connect to thesignalHandlerException() signal to catch such an exception.
UsenewQMetaObject() to wrap aQMetaObject; this gives you a "script representation" of aQObject-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; seescriptValueFromQMetaObject().
For more information aboutQObject integration, seeMaking Applications Scriptable
UsenewVariant() to wrap aQVariant. 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 callingsetDefaultPrototype(); the prototype object defines the scripting API for the C++ type. Unlike theQObject integration, there is no automatic binding possible here; i.e. you have to create the scripting API yourself, for example by using theQScriptable class.
UsefromScriptValue() to cast from aQScriptValue to another type, andtoScriptValue() to create aQScriptValue from another value. You can specify how the conversion of C++ types is to be performed withqScriptRegisterMetaType() andqScriptRegisterSequenceMetaType(). By default, Qt Script will useQVariant to store values of custom types.
UseimportExtension() to import plugin-based extensions into the engine. CallavailableExtensions() to obtain a list naming all the available extensions, andimportedExtensions() to obtain a list naming only those extensions that have been imported.
CallpushContext() to open up a new variable scope, andpopContext() 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.
UsenewFunction() 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 signatureQScriptEngine::FunctionSignature. You may then pass the function as argument tonewFunction(). 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)");
If you need to evaluate possibly long-running scripts from the main (GUI) thread, you should first callsetProcessEventsInterval() to make sure that the GUI stays responsive. You can abort a currently running script by callingabortEvaluation(). You can determine whether an engine is currently running a script by callingisEvaluating().
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.
ThecollectGarbage() function can be called to explicitly request garbage collection.
ThereportAdditionalMemoryCost() function can be called to indicate that a Qt Script object occupies memory that isn't managed by the scripting environment. Reporting the additional cost makes it more likely that the garbage collector will be triggered. This can be useful, for example, when many custom, native Qt Script objects are allocated.
Since Qt 4.4, you can be notified of events pertaining to script execution (e.g. script function calls and statement execution) through theQScriptEngineAgent interface; see thesetAgent() function. This can be used to implement debugging and profiling of aQScriptEngine.
See alsoQScriptValue,QScriptContext, andQScriptEngineAgent.
The function signatureQScriptValue f(QScriptContext *, QScriptEngine *).
A function with such a signature can be passed toQScriptEngine::newFunction() to wrap the function.
The function signatureQScriptValue f(QScriptContext *, QScriptEngine *, void *).
A function with such a signature can be passed toQScriptEngine::newFunction() to wrap the function.
These flags specify options when wrapping aQObject pointer withnewQObject().
| Constant | Value | Description |
|---|---|---|
QScriptEngine::ExcludeChildObjects | 0x0001 | The script object will not expose child objects as properties. |
QScriptEngine::ExcludeSuperClassMethods | 0x0002 | The script object will not expose signals and slots inherited from the superclass. |
QScriptEngine::ExcludeSuperClassProperties | 0x0004 | The script object will not expose properties inherited from the superclass. |
QScriptEngine::ExcludeSuperClassContents | 0x0006 | Shorthand form for ExcludeSuperClassMethods | ExcludeSuperClassProperties |
QScriptEngine::ExcludeDeleteLater | 0x0010 | The script object will not expose theQObject::deleteLater() slot. |
QScriptEngine::ExcludeSlots | 0x0020 | The script object will not expose theQObject's slots. |
QScriptEngine::AutoCreateDynamicProperties | 0x0100 | Properties that don't already exist in theQObject will be created as dynamic properties of that object, rather than as properties of the script object. |
QScriptEngine::PreferExistingWrapperObject | 0x0200 | If a wrapper object with the requested configuration already exists, return that object. |
QScriptEngine::SkipMethodsInEnumeration | 0x0008 | Don't include methods (signals and slots) when enumerating the object's properties. |
The QObjectWrapOptions type is a typedef forQFlags<QObjectWrapOption>. It stores an OR combination of QObjectWrapOption values.
This enum specifies the ownership when wrapping a C++ value, e.g. by usingnewQObject().
| Constant | Value | Description |
|---|---|---|
QScriptEngine::QtOwnership | 0 | The standard Qt ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained inObject Trees & Ownership.) |
QScriptEngine::ScriptOwnership | 1 | The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value). |
QScriptEngine::AutoOwnership | 2 | If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership). |
Constructs aQScriptEngine object.
TheglobalObject() is initialized to have properties as described inECMA-262, Section 15.1.
Constructs aQScriptEngine object with the givenparent.
TheglobalObject() is initialized to have properties as described inECMA-262, Section 15.1.
[virtual]QScriptEngine::~QScriptEngine()Destroys thisQScriptEngine.
Aborts any script evaluation currently taking place in this engine. The givenresult is passed back as the result of the evaluation (i.e. it is returned from the call toevaluate() 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.
This function was introduced in Qt 4.4.
See alsoevaluate(),isEvaluating(), andsetProcessEventsInterval().
Returns the agent currently installed on this engine, or 0 if no agent is installed.
This function was introduced in Qt 4.4.
See alsosetAgent().
Returns a list naming the available extensions that can be imported using theimportExtension() function. This list includes extensions that have been imported.
This function was introduced in Qt 4.4.
See alsoimportExtension() andimportedExtensions().
[static]QScriptSyntaxCheckResult QScriptEngine::checkSyntax(constQString & program)Checks the syntax of the givenprogram. Returns aQScriptSyntaxCheckResult object that contains the result of the check.
This function was introduced in Qt 4.5.
Clears any uncaught exceptions in this engine.
This function was introduced in Qt 4.4.
See alsohasUncaughtException().
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 theQScriptEngine 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 alsoreportAdditionalMemoryCost().
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 inQScriptEngine::FunctionSignature.
Returns the default prototype associated with the givenmetaTypeId, or an invalidQScriptValue if no default prototype has been set.
See alsosetDefaultPrototype().
Evaluatesprogram, usinglineNumber as the base line number, and returns the result of the evaluation.
The script code will be evaluated in the current context.
The evaluation ofprogram can cause an exception in the engine; in this case the return value will be the exception that was thrown (typically anError object). You can callhasUncaughtException() to determine if an exception occurred in the last call to evaluate().
lineNumber is used to specify a starting line number forprogram; line number information reported by the engine that pertain to this evaluation (e.g.uncaughtExceptionLineNumber()) will be based on this argument. For example, ifprogram consists of two lines of code, and the statement on the second line causes a script exception,uncaughtExceptionLineNumber() would return the givenlineNumber 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 alsocanEvaluate(),hasUncaughtException(),isEvaluating(), andabortEvaluation().
Evaluates the givenprogram and returns the result of the evaluation.
This function was introduced in Qt 4.7.
Returns the givenvalue converted to the template typeT.
Note thatT must be known toQMetaType.
SeeConversion Between QtScript and C++ Types for a description of the built-in type conversion provided byQtScript.
See alsotoScriptValue() andqScriptRegisterMetaType().
Returns this engine's Global Object.
By default, the Global Object contains the built-in objects that are part ofECMA-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.
See alsosetGlobalObject().
Returns true if the last script evaluation resulted in an uncaught exception; otherwise returns false.
The exception state is cleared whenevaluate() is called.
See alsouncaughtException() anduncaughtExceptionLineNumber().
Imports the givenextension into thisQScriptEngine. ReturnsundefinedValue() if the extension was successfully imported. You can callhasUncaughtException() to check if an error occurred; in that case, the return value is the value that was thrown by the exception (usually anError object).
QScriptEngine ensures that a particular extension is only imported once; subsequent calls to importExtension() with the same extension name will do nothing and returnundefinedValue().
See alsoavailableExtensions(),QScriptExtensionPlugin, andCreating QtScript Extensions.
Returns a list naming the extensions that have been imported using theimportExtension() function.
This function was introduced in Qt 4.4.
See alsoavailableExtensions().
Installs translator functions on the givenobject, or on the Global Object if no object is specified.
The relation between Qt Script translator functions and C++ translator functions is described in the following table:
| Script Function | Corresponding C++ Function |
|---|---|
| qsTr() | QObject::tr() |
| QT_TR_NOOP() | QT_TR_NOOP() |
| qsTranslate() | QCoreApplication::translate() |
| QT_TRANSLATE_NOOP() | QT_TRANSLATE_NOOP() |
| qsTrId() (since 4.7) | qtTrId() |
| QT_TRID_NOOP() (since 4.7) | QT_TRID_NOOP() |
This function was introduced in Qt 4.5.
See alsoInternationalization with Qt.
Returns true if this engine is currently evaluating a script, otherwise returns false.
This function was introduced in Qt 4.4.
See alsoevaluate() andabortEvaluation().
Creates aQtScript object of class Array with the givenlength.
See alsonewObject().
Creates aQtScript object of class Date with the givenvalue (the number of milliseconds since 01 January 1970, UTC).
Creates aQtScript object of class Date from the givenvalue.
See alsoQScriptValue::toDateTime().
Creates aQScriptValue that wraps a native (C++) function.fun must be a C++ function with signatureQScriptEngine::FunctionSignature.length is the number of arguments thatfun expects; this becomes thelength property of the createdQScriptValue.
Note thatlength 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 theargumentCount() of theQScriptContext associated with the invocation to determine the actual number of arguments passed.
Aprototype 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 flagsQScriptValue::PropertyGetter andQScriptValue::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 inQt's Property System). Example:
staticQScriptValue 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),QScriptValue::PropertyGetter|QScriptValue::PropertySetter);
When the propertyfoo 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 offoo 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 orQScriptValue::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 alsoQScriptValue::call().
Creates a constructor function fromfun, with the givenlength. Theprototype property of the resulting function is set to be the givenprototype. Theconstructor property ofprototype 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 publicprototype 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 thedefaultPrototype() of that type. Example:
QScriptValue Foo(QScriptContext*context,QScriptEngine*engine){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()" expressionreturn engine->undefinedValue(); }else {// not called as "new Foo()", just "Foo()"// create our own object and return that oneQScriptValue 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 {... };Q_DECLARE_METATYPE(Bar)QScriptValue constructBar(QScriptContext*context,QScriptEngine*engine){ Bar bar;// initialize from arguments in context, if desired...return engine->toScriptValue(bar);}class BarPrototype :publicQObject,publicQScriptable{// provide the scriptable interface of this type using slots and properties...};...// create and register the Bar prototype and constructor in the engineBarPrototype*barPrototypeObject=new BarPrototype(...);QScriptValue barProto= engine->newQObject(barPrototypeObject);engine->setDefaultPrototype(qMetaTypeId<Bar>, barProto);QScriptValue barCtor= engine->newFunction(constructBar, barProto);engine->globalObject().setProperty("Bar", barCtor);
Creates aQtScript object of class Object.
The prototype of the created object will be the Object prototype object.
See alsonewArray() andQScriptValue::setProperty().
This is an overloaded function.
Creates aQtScript Object of the given class,scriptClass.
The prototype of the created object will be the Object prototype object.
data, if specified, is set as the internal data of the new object (usingQScriptValue::setData()).
This function was introduced in Qt 4.4.
See alsoQScriptValue::scriptClass() andreportAdditionalMemoryCost().
Creates aQtScript object that represents aQObject class, using the the givenmetaObject and constructorctor.
Enums ofmetaObject (declared withQ_ENUMS) are available as properties of the createdQScriptValue. 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=newQObject(parent);return engine->newQObject(object,QScriptEngine::ScriptOwnership);}...QScriptValue ctor= engine.newFunction(mySpecialQObjectConstructor);QScriptValue metaObject= engine.newQMetaObject(&QObject::staticMetaObject, ctor);engine.globalObject().setProperty("QObject", metaObject);QScriptValue result= engine.evaluate("new QObject()");
See alsonewQObject() andscriptValueFromQMetaObject().
Creates aQtScript object that wraps the givenQObjectobject, using the givenownership. The givenoptions control various aspects of the interaction with the resulting script object.
Signals and slots, properties and children ofobject are available as properties of the createdQScriptValue. For more information, see theQtScript documentation.
Ifobject is a null pointer, this function returnsnullValue().
If a default prototype has been registered for theobject's class (or its superclass, recursively), the prototype of the new script object will be set to be that default prototype.
If the givenobject is deleted outside ofQtScript's control, any attempt to access the deletedQObject's members through theQtScript wrapper object (either by script code or C++) will result in a script exception.
See alsoQScriptValue::toQObject() andreportAdditionalMemoryCost().
This is an overloaded function.
Initializes the givenscriptObject to hold the givenqtObject, and returns thescriptObject.
This function enables you to "promote" a plain Qt Script object (created by thenewObject() function) to aQObject proxy, or to replace theQObject contained inside an object previously created by thenewQObject() function.
The prototype() of thescriptObject will remain unchanged.
IfscriptObject is not an object, this function behaves like the normalnewQObject(), i.e. it creates a new script object and returns it.
This function is useful when you want to provide a script constructor for aQObject-based class. If your constructor is invoked in anew expression (QScriptContext::isCalledAsConstructor() returns true), you can passQScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.
This function was introduced in Qt 4.4.
See alsoreportAdditionalMemoryCost().
Creates aQtScript object of class RegExp with the givenregexp.
See alsoQScriptValue::toRegExp().
Creates aQtScript object of class RegExp with the givenpattern andflags.
The legal flags are 'g' (global), 'i' (ignore case), and 'm' (multiline).
Creates aQtScript object holding the given variantvalue.
If a default prototype has been registered with the meta type id ofvalue, then the prototype of the created object will be that prototype; otherwise, the prototype will be the Object prototype object.
See alsosetDefaultPrototype(),QScriptValue::toVariant(), andreportAdditionalMemoryCost().
This is an overloaded function.
Initializes the given Qt Scriptobject to hold the given variantvalue, and returns theobject.
This function enables you to "promote" a plain Qt Script object (created by thenewObject() function) to a variant, or to replace the variant contained inside an object previously created by thenewVariant() function.
The prototype() of theobject will remain unchanged.
Ifobject is not an object, this function behaves like the normalnewVariant(), 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 anew expression (QScriptContext::isCalledAsConstructor() returns true), you can passQScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.
This function was introduced in Qt 4.4.
See alsoreportAdditionalMemoryCost().
Returns aQScriptValue of the primitive type Null.
See alsoundefinedValue().
Pops the current execution context and restores the previous one. This function must be used in conjunction withpushContext().
See alsopushContext().
Returns the interval in milliseconds between calls toQCoreApplication::processEvents() while the interpreter is running.
See alsosetProcessEventsInterval().
Enters a new execution context and returns the associatedQScriptContext object.
Once you are done with the context, you should callpopContext() to restore the old context.
By default, the `this' object of the new context is the Global Object. The context'scallee() 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'sactivationObject() to initialize local variables that will be available to scripts. Example:
QScriptEngine engine;QScriptContext*context= engine.pushContext();context->activationObject().setProperty("myArg",123);engine.evaluate("var tmp = myArg + 42");...engine.popContext();
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 alsopopContext().
Reports an additional memory cost of the givensize, measured in bytes, to the garbage collector.
This function can be called to indicate that a Qt Script object has memory associated with it that isn't managed by Qt Script itself. Reporting the additional cost makes it more likely that the garbage collector will be triggered.
Note that if the additional memory is shared with objects outside the scripting environment, the cost should not be reported, since collecting the Qt Script object would not cause the memory to be freed anyway.
Negativesize values are ignored, i.e. this function can't be used to report that the additional memory has been deallocated.
This function was introduced in Qt 4.7.
See alsocollectGarbage().
Creates aQScriptValue that represents the Qt classT.
This function is used in combination with one of theQ_SCRIPT_DECLARE_QMETAOBJECT() macro. Example:
Q_SCRIPT_DECLARE_QMETAOBJECT(QLineEdit,QWidget*)...QScriptValue lineEditClass= engine.scriptValueFromQMetaObject<QLineEdit>();engine.globalObject().setProperty("QLineEdit", lineEditClass);
See alsoQScriptEngine::newQMetaObject().
Installs the givenagent on this engine. The agent will be notified of various events pertaining to script execution. This is useful when you want to find out exactly what the engine is doing, e.g. whenevaluate() is called. The agent interface is the basis of tools like debuggers and profilers.
The engine maintains ownership of theagent.
Calling this function will replace the existing agent, if any.
This function was introduced in Qt 4.4.
See alsoagent().
Sets the default prototype of the C++ type identified by the givenmetaTypeId toprototype.
The default prototype provides a script interface for values of typemetaTypeId when a value of that type is accessed from script code. Whenever the script engine (implicitly or explicitly) creates aQScriptValue from a value of typemetaTypeId, the default prototype will be set as theQScriptValue's prototype.
Theprototype object itself may be constructed using one of two principal techniques; the simplest is to subclassQScriptable, which enables you to define the scripting API of the type throughQObject properties and slots. Another possibility is to create a script object by callingnewObject(), and populate the object with the desired properties (e.g. native functions wrapped withnewFunction()).
See alsodefaultPrototype(),qScriptRegisterMetaType(),QScriptable, andDefault Prototypes Example.
Sets this engine's Global Object to be the givenobject. Ifobject is not a valid script object, this function does nothing.
When setting a custom global object, you may want to useQScriptValueIterator 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.
This function was introduced in Qt 4.5.
See alsoglobalObject().
Sets the interval between calls toQCoreApplication::processEvents tointerval 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 timeQCoreApplication::processEvents() is called.
The default value is -1, which disables event processing during interpreter execution.
You can useQCoreApplication::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 callabortEvaluation() when you detect that the script has been running for a long time without completing.
See alsoprocessEventsInterval().
[signal]void QScriptEngine::signalHandlerException(constQScriptValue & exception)This signal is emitted when a script function connected to a signal causes anexception.
This function was introduced in Qt 4.4.
See alsoqScriptConnect().
Converts the givenvalue to an object, if such a conversion is possible; otherwise returns an invalidQScriptValue. The conversion is performed according to the following table:
| Input Type | Result |
|---|---|
| Undefined | An invalidQScriptValue. |
| Null | An invalidQScriptValue. |
| 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). |
This function was introduced in Qt 4.5.
See alsonewObject().
Creates aQScriptValue with the givenvalue.
Note that the template typeT must be known toQMetaType.
SeeConversion Between QtScript and C++ Types for a description of the built-in type conversion provided byQtScript. By default, the types that are not specially handled byQtScript are represented asQVariants (e.g. thevalue is passed tonewVariant()); you can change this behavior by installing your own type conversion functions withqScriptRegisterMetaType().
See alsofromScriptValue() andqScriptRegisterMetaType().
Returns a handle that represents the given string,str.
QScriptString can be used to quickly look up properties, and compare property names, of script objects.
This function was introduced in Qt 4.4.
See alsoQScriptValue::property().
Returns the current uncaught exception, or an invalidQScriptValue if there is no uncaught exception.
The exception value is typically anError object; in that case, you can call toString() on the return value to obtain an error message.
See alsohasUncaughtException() anduncaughtExceptionLineNumber().
Returns a human-readable backtrace of the last uncaught exception.
It is in the form<function-name>()@<file-name>:<line-number>.
See alsouncaughtException().
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 toevaluate().
See alsohasUncaughtException().
Returns aQScriptValue of the primitive type Undefined.
See alsonullValue().
The function signatureQScriptValue f(QScriptContext *, QScriptEngine *).
A function with such a signature can be passed toQScriptEngine::newFunction() to wrap the function.
The function signatureQScriptValue f(QScriptContext *, QScriptEngine *, void *).
A function with such a signature can be passed toQScriptEngine::newFunction() to wrap the function.
Creates a connection from thesignal in thesender to the givenfunction. Ifreceiver 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.
This function was introduced in Qt 4.4.
See alsoqScriptDisconnect() andQScriptEngine::signalHandlerException().
Disconnects thesignal in thesender from the given (receiver,function) pair. Returns true if the connection is successfully broken; otherwise returns false.
This function was introduced in Qt 4.4.
See alsoqScriptConnect().
Registers the typeT in the givenengine.toScriptValue must be a function that will convert from a value of typeT to aQScriptValue, andfromScriptValue a function that does the opposite.prototype, if valid, is the prototype that's set on QScriptValues returned bytoScriptValue.
Returns the internal ID used byQMetaType.
You only need to call this function if you want to provide custom conversion of values of typeT, i.e. if the defaultQVariant-based representation and conversion is not appropriate. (Note that customQObject-derived types also fall in this category; e.g. for aQObject-derived class called MyObject, you probably want to define conversion functions for MyObject* that utilizeQScriptEngine::newQObject() andQScriptValue::toQObject().)
If you only want to define a common script interface for values of typeT, and don't care how those values are represented (i.e. storing them inQVariants is fine), usesetDefaultPrototype() instead; this will minimize conversion costs.
You need to declare the custom type first withQ_DECLARE_METATYPE().
After a type has been registered, you can convert from aQScriptValue to that type usingfromScriptValue(), and create aQScriptValue from a value of that type usingtoScriptValue(). 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 typeMyStruct. Here's the C++ type:
struct MyStruct {int x;int y;};
We must declare it so that the type will be known toQMetaType:
Q_DECLARE_METATYPE(MyStruct)
Next, theMyStruct conversion functions. We represent theMyStruct 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(constQScriptValue&obj, MyStruct&s){ s.x= obj.property("x").toInt32(); s.y= obj.property("y").toInt32();}
Now we can registerMyStruct with the engine:
qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue);
Working withMyStruct 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 alsoqScriptRegisterSequenceMetaType() andqRegisterMetaType().
Registers the sequence typeT in the givenengine. This function provides conversion functions that convert betweenT and Qt ScriptArray objects.T must provide a const_iterator class and begin(), end() and push_back() functions. Ifprototype is valid, it will be set as the prototype ofArray objects due to conversion fromT; otherwise, the standardArray prototype will be used.
Returns the internal ID used byQMetaType.
You need to declare the container type first withQ_DECLARE_METATYPE(). If the element type isn't a standard Qt/C++ type, it must be declared usingQ_DECLARE_METATYPE() as well. Example:
Q_DECLARE_METATYPE(QVector<int>)...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 alsoqScriptRegisterMetaType().
Creates an array in the form of aQScriptValue using the givenengine with the givencontainer of template typeContainer.
TheContainer type must provide aconst_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 aQScriptValue. SeeConversion Between QtScript and C++ Types for more information about the restrictions on types that can be used withQScriptValue.
This function was introduced in Qt 4.3.
See alsoQScriptEngine::fromScriptValue().
Copies the elements in the sequence specified byvalue to the givencontainer of template typeContainer.
Thevalue used is typically an array, but any container can be copied as long as it provides alength 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 aQScriptValue. SeeConversion Between QtScript and C++ Types for more information about the restrictions on types that can be used withQScriptValue.
This function was introduced in Qt 4.3.
See alsoqscriptvalue_cast().
Declares the givenQMetaObject. Used in combination withQScriptEngine::scriptValueFromQMetaObject() to make enums and instantiation ofQMetaObject available to script code. The constructor generated by this macro takes a single argument of typeArgType; typically the argument is the parent type of the new instance, in which caseArgType isQWidget* orQObject*. Objects created by the constructor will haveQScriptEngine::AutoOwnership ownership.
This function was introduced in Qt 4.3.
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.