QScriptEngine Class Reference |
Constant | Value | Description |
---|---|---|
QScriptEngine::ExcludeChildObjects | 0x0001 | The script object will not expose child objects as properties. |
QScriptEngine::ExcludeSuperClassMethods | 0x0002 | The script object will not expose signals and slots inherited from the superclass. |
QScriptEngine::ExcludeSuperClassProperties | 0x0004 | The script object will not expose properties inherited from the superclass. |
QScriptEngine::AutoCreateDynamicProperties | 0x0100 | Properties that don't already exist in the QObject will be created as dynamic properties of that object, rather than as properties of the script object. |
The QObjectWrapOptions type is a typedef for QFlags<QObjectWrapOption>. It stores an OR combination of QObjectWrapOption values.
This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().
Constant | Value | Description |
---|---|---|
QScriptEngine::QtOwnership | 0 | The standard Qt ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in Object Trees and Object Ownership.) |
QScriptEngine::ScriptOwnership | 1 | The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value). |
QScriptEngine::AutoOwnership | 2 | If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership). |
Constructs a QScriptEngine object.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
Constructs a QScriptEngine object with the given parent.
The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.
Destroys this QScriptEngine.
Returns true if program can be evaluated; i.e. the code is sufficient to determine whether it appears to be a syntactically correct program, or contains a syntax error.
This function returns false if program is incomplete; i.e. the input is syntactically correct up to the point where the input is terminated.
Note that this function only does a static check of program; e.g. it does not check whether references to variables are valid, and so on.
A typical usage of canEvaluate() is to implement an interactive interpreter for QtScript. The user is repeatedly queried for individual lines of code; the lines are concatened internally, and only when canEvaluate() returns true for the resulting program is it passed to evaluate().
The following are some examples to illustrate the behavior of canEvaluate(). (Note that all example inputs are assumed to have an explicit newline as their last character, since otherwise the QtScript parser would automatically insert a semi-colon character at the end of the input, and this could cause canEvaluate() to produce different results.)
Given the input
if (hello && world) print("hello world");
canEvaluate() will return true, since the program appears to be complete.
Given the input
if (hello &&
canEvaluate() will return false, since the if-statement is not complete, but is syntactically correct so far.
Given the input
0 = 0
canEvaluate() will return true, but evaluate() will throw a SyntaxError given the same input.
Given the input
./test.js
canEvaluate() will return true, even though the code is clearly not syntactically valid QtScript code. evaluate() will throw a SyntaxError when this code is evaluated.
Given the input
foo["bar"]
canEvaluate() will return true, but evaluate() will throw a ReferenceError if foo is not defined in the script environment.
See also evaluate().
Runs the garbage collector.
The garbage collector will attempt to reclaim memory by locating and disposing of objects that are no longer reachable in the script environment.
Normally you don't need to call this function; the garbage collector will automatically be invoked when the QScriptEngine decides that it's wise to do so (i.e. when a certain number of new objects have been created). However, you can call this function to explicitly request that garbage collection should be performed as soon as possible.
Returns the current context.
The current context is typically accessed to retrieve the arguments and `this' object in native functions; for convenience, it is available as the first argument in QScriptEngine::FunctionSignature.
Returns the default prototype associated with the given metaTypeId, or an invalid QScriptValue if no default prototype has been set.
See also setDefaultPrototype().
Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation.
The script code will be evaluated in the current context.
The evaluation of program can cause an exception in the engine; in this case the return value will be the exception that was thrown (typically an Error object). You can call hasUncaughtException() to determine if an exception occurred in the last call to evaluate().
lineNumber is used to specify a starting line number for program; line number information reported by the engine that pertain to this evaluation (e.g. uncaughtExceptionLineNumber()) will be based on this argument. For example, if program consists of two lines of code, and the statement on the second line causes a script exception, uncaughtExceptionLineNumber() would return the given lineNumber plus one. When no starting line number is specified, line numbers will be 1-based.
fileName is used for error reporting. For example in error objects the file name is accessible through the "fileName" property if it's provided with this function.
See also canEvaluate() and hasUncaughtException().
Returns 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.
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().
Returns this engine's Global Object.
The Global Object contains the built-in objects that are part of ECMA-262, such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code. Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.
Returns true if the last script evaluation (whether direct or indirect) resulted in an uncaught exception; otherwise returns false.
The exception state is cleared every time a script function call is done in the engine, or when evaluate() is called.
See also uncaughtException(), uncaughtExceptionLineNumber(), and uncaughtExceptionBacktrace().
Imports the given extension into this QScriptEngine. Returns undefinedValue() if the extension was successfully imported. You can call hasUncaughtException() to check if an error occurred; in that case, the return value is the value that was thrown by the exception (usually an Error object).
QScriptEngine ensures that a particular extension is only imported once; subsequent calls to importExtension() with the same extension name will do nothing and return undefinedValue().
See also QScriptExtensionPlugin and Creating QtScript Extensions.
Creates a QtScript object of class Array with the given length.
See also newObject().
Creates a QtScript object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC).
This is an overloaded member function, provided for convenience.
Creates a QtScript object of class Date from the given value.
See also QScriptValue::toDateTime().
Creates a 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.
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),
QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
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().
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.
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:
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()" 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 { ... }; 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 : 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);
Creates a QtScript object of class Object.
The prototype of the created object will be the Object prototype object.
See also newArray() and QScriptValue::setProperty().
Creates a QtScript object that represents a QObject class, using the the given metaObject and constructor ctor.
Enums of metaObject are available as properties of the created QScriptValue. When the class is called as a function, ctor will be called to create a new instance of the class.
See also newQObject().
Creates a QtScript object that wraps the given QObject object, using the given ownership. The given options control various aspects of the interaction with the resulting script object.
Signals and slots, properties and children of object are available as properties of the created QScriptValue. For more information, see the QtScript documentation.
If object is a null pointer, this function returns nullValue().
If the given object is deleted outside of QtScript's control, any attempt to access the deleted QObject's members through the QtScript wrapper object (either by script code or C++) will result in a script exception.
See also QScriptValue::toQObject().
Creates a QtScript object of class RegExp with the given regexp.
See also QScriptValue::toRegExp().
This is an overloaded member function, provided for convenience.
Creates a QtScript object of class RegExp with the given pattern and flags.
Creates a QtScript object holding the given variant value.
If a default prototype has been registered with the meta type id of value, then the prototype of the created object will be that prototype; otherwise, the prototype will be the Object prototype object.
See also setDefaultPrototype() and QScriptValue::toVariant().
Returns a QScriptValue of the primitive type Null.
See also undefinedValue().
Pops the current execution context and restores the previous one. This function must be used in conjunction with pushContext().
See also pushContext().
Returns the interval in milliseconds between calls to QCoreApplication::processEvents() while the interpreter is running.
See also setProcessEventsInterval().
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:
QScriptEngine engine; QScriptContext *context = engine.pushContext(); context->activationObject().setProperty("myArg", QScriptValue(&engine, 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.
See also popContext().
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.
Sets the default prototype of the given metaTypeId to prototype.
The default prototype provides a script interface for values of type metaTypeId when a value of that type is accessed from script code. Whenever the script engine (implicitly or explicitly) creates a QScriptValue from a value of type metaTypeId, the default prototype will be set as the QScriptValue's prototype.
See also defaultPrototype(), qScriptRegisterMetaType(), QScriptable, and Default Prototypes Example.
Sets the interval between calls to QCoreApplication::processEvents to interval milliseconds.
While the interpreter is running, all event processing is by default blocked. This means for instance that the gui will not be updated and timers will not be fired. To allow event processing during interpreter execution one can specify the processing interval to be a positive value, indicating the number of milliseconds between each time QCoreApplication::processEvents() is called.
The default value is -1, which disables event processing during interpreter execution.
See also processEventsInterval().
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().
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().
Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception.
The exception value is typically an Error object; in that case, you can call toString() on the return value to obtain an error message.
See also hasUncaughtException(), uncaughtExceptionLineNumber(), and uncaughtExceptionBacktrace().
Returns a human-readable backtrace of the last uncaught exception.
Each line is of the form <function-name>(<arguments>)@<file-name>:<line-number>.
See also uncaughtException().
Returns the line number where the last uncaught exception occurred.
Line numbers are 1-based, unless a different base was specified as the second argument to evaluate().
See also hasUncaughtException() and uncaughtExceptionBacktrace().
Returns a QScriptValue of the primitive type Undefined.
See also nullValue().
The function signature QScriptValue f(QScriptContext *, QScriptEngine *).
A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.
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. If you only want to define a common script interface for values of type T, and don't care how those values are represented, use setDefaultPrototype() instead.
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:
Q_DECLARE_METATYPE(MyStruct)
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", 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 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() and qRegisterMetaType().
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);
...
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().
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.
This function was introduced in Qt 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.
This function was introduced in Qt 4.3.
See also qScriptValueFromValue().
Creates a QScriptValue using the given engine with the given value of template type T.
This function is equivalent to QScriptEngine::toScriptValue(). It is provided as a work-around for MSVC 6, which doesn't support member template functions.
This function was introduced in Qt 4.3.
See also qScriptValueToValue().
Copies the elements in the sequence specified by value to the given container of template type Container.
The value used is typically an array, but any container can be copied as long as it provides a length property describing how many elements it contains.
Additionally, the type of each element in the sequence must be suitable for conversion to a C++ type from a QScriptValue. See Conversion Between QtScript and C++ Types for more information about the restrictions on types that can be used with QScriptValue.
This function was introduced in Qt 4.3.
See also qscriptvalue_cast().
Returns the given value converted to the template type T.
This function is equivalent to QScriptEngine::fromScriptValue(). It is provided as a work-around for MSVC 6, which doesn't support member template functions.
This function was introduced in Qt 4.3.
See also qScriptValueFromValue().
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*. Objects created by the constructor will have QScriptEngine::AutoOwnership ownership.
This function was introduced in Qt 4.3.
Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. | Qt 4.3 | |
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD. | ||
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP ! |
Copyright © 2000-2012 - www.developpez.com