- class QJSValue¶
The
QJSValue
class acts as a container for Qt/JavaScript data types. More…Synopsis¶
Methods¶
def
__init__()
def
call()
def
deleteProperty()
def
equals()
def
errorType()
def
hasOwnProperty()
def
hasProperty()
def
isArray()
def
isBool()
def
isCallable()
def
isDate()
def
isError()
def
isNull()
def
isNumber()
def
isObject()
def
isQMetaObject()
def
isQObject()
def
isRegExp()
def
isString()
def
isUndefined()
def
isUrl()
def
isVariant()
def
property()
def
prototype()
def
setProperty()
def
setPrototype()
def
strictlyEquals()
def
toBool()
def
toDateTime()
def
toInt()
def
toNumber()
def
toPrimitive()
def
toQMetaObject()
def
toQObject()
def
toString()
def
toUInt()
def
toVariant()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QJSValue
supports the types defined in the ECMA-262 standard: The primitive types, which are Undefined, Null, Boolean, Number, and String; and the Object and Array types. Additionally, built-in support is provided for Qt/C++ types such as QVariant and QObject.For the object-based types (including Date and RegExp), use the newT() functions in
QJSEngine
(e.g.newObject()
) to create aQJSValue
of the desired type. For the primitive types, use one of theQJSValue
constructor overloads. For other types, e.g. registered gadget types such as QPoint, you can usetoScriptValue
.The methods named isT() (e.g.
isBool()
,isUndefined()
) can be used to test if a value is of a certain type. The methods named toT() (e.g.toBool()
,toString()
) can be used to convert aQJSValue
to another type. You can also use the generic qjsvalue_cast() function.Object values have zero or more properties which are themselves QJSValues. Use
setProperty()
to set a property of an object, and callproperty()
to retrieve the value of a property.myEngine = QJSEngine() myObject = myEngine.newObject() myOtherObject = myEngine.newObject() myObject.setProperty("myChild", myOtherObject) myObject.setProperty("name", "John Doe")
If you want to iterate over the properties of a script object, use the
QJSValueIterator
class.Object values have an internal
prototype
property, which can be accessed withprototype()
andsetPrototype()
.Function objects (objects for which
isCallable()
) returns true) can be invoked by callingcall()
. Constructor functions can be used to construct new objects by callingcallAsConstructor()
.Use
equals()
orstrictlyEquals()
to compare aQJSValue
to another.Note that a
QJSValue
for whichisObject()
is true only carries a reference to an actual object; copying theQJSValue
will only copy the object reference, not the object itself. If you want to clone an object (i.e. copy an object’s properties to another object), you can do so with the help of afor-in
statement in script code, orQJSValueIterator
in C++.Working With Arrays¶
To create an array using
QJSValue
, usenewArray()
:// Assumes that this class was declared in QML. QJSValue jsArray = engine->newArray(3);
To set individual elements in the array, use the
setProperty(quint32 arrayIndex, const QJSValue &value)
overload. For example, to fill the array above with integers:for (int i = 0; i < 3; ++i) { jsArray.setProperty(i, QRandomGenerator::global().generate()); }
To determine the length of the array, access the
"length"
property. To access array elements, use theproperty(quint32 arrayIndex)
overload. The following code reads the array we created above back into a list:QVector<int> integers; const int length = jsArray.property("length").toInt(); for (int i = 0; i < length; ++i) { integers.append(jsArray.property(i).toInt()); }
Converting to JSON¶
It’s possible to convert a
QJSValue
to a JSON type. For example, to convert to an array, usefromScriptValue()
:const QJsonValue jsonValue = engine.fromScriptValue<QJsonValue>(jsValue); const QJsonArray jsonArray = jsonValue.toArray();
See also
- class SpecialValue¶
This enum is used to specify a single-valued type.
Constant
Description
QJSValue.UndefinedValue
An undefined value.
QJSValue.NullValue
A null value.
- class ErrorType¶
Use this enum for JavaScript language-specific types of Error objects.
They may be useful when emulating language features in C++ requires the use of specialized exception types. In addition, they may help to more clearly communicate certain typical conditions, instead of throwing a generic JavaScript exception. For example, code that deals with networking and resource locators may find it useful to propagate errors related to malformed locators using the URIError type.
Constant
Description
QJSValue.GenericError
A generic Error object, but not of a specific sub-type.
QJSValue.RangeError
A value did not match the expected set or range.
QJSValue.ReferenceError
A non-existing variable referenced.
QJSValue.SyntaxError
An invalid token or sequence of tokens was encountered that does not conform with the syntax of the language.
QJSValue.TypeError
An operand or argument is incompatible with the type expected.
QJSValue.URIError
A URI handling function was used incorrectly or the URI provided is malformed.
- class ObjectConversionBehavior¶
This enum is used to specify how JavaScript objects and symbols without an equivalent native Qt type should be treated when converting to QVariant.
Constant
Description
QJSValue.ConvertJSObjects
A best-effort, possibly lossy, conversion is attempted. Symbols are converted to QString.
QJSValue.RetainJSObjects
The value is retained as
QJSValue
wrapped in QVariant.Added in version 6.1.
- __init__([value=QJSValue.SpecialValue.UndefinedValue])¶
- Parameters:
value –
SpecialValue
Constructs a new
QJSValue
with a specialvalue
.- __init__(value)
- Parameters:
value – bool
Constructs a new
QJSValue
with a booleanvalue
.- __init__(other)
- Parameters:
other –
QJSValue
Constructs a new
QJSValue
that is a copy ofother
.Note that if
other
is an object (i.e.,isObject()
would return true), then only a reference to the underlying object is copied into the new script value (i.e., the object itself is not copied).- __init__(value)
- Parameters:
value –
QLatin1String
Constructs a new
QJSValue
with a stringvalue
.- __init__(value)
- Parameters:
value – str
Constructs a new
QJSValue
with a stringvalue
.- __init__(str)
- Parameters:
str – str
Constructs a new
QJSValue
with a stringvalue
.- __init__(value)
- Parameters:
value – float
Constructs a new
QJSValue
with a numbervalue
.- __init__(value)
- Parameters:
value – int
Constructs a new
QJSValue
with a numbervalue
.- __init__(value)
- Parameters:
value – int
Constructs a new
QJSValue
with a numbervalue
.Calls this
QJSValue
as a function, passingargs
as arguments to the function, and using the globalObject() as the “this”-object. Returns the value returned from the function.If this
QJSValue
is not callable, call() does nothing and returns an undefinedQJSValue
.Calling call() can cause an exception to occur in the script engine; in that case, call() returns the value that was thrown (typically an
Error
object). You can callisError()
on the return value to determine whether an exception occurred.- callAsConstructor([args=QJSValueList()])¶
- Parameters:
args – .list of QJSValue
- Return type:
Creates a new
Object
and calls thisQJSValue
as a constructor, using the created object as the `this’ object and passingargs
as arguments. If the return value from the constructor call is an object, then that object is returned; otherwise the default constructed object is returned.If this
QJSValue
is not a function, callAsConstructor() does nothing and returns an undefinedQJSValue
.Calling this function can cause an exception to occur in the script engine; in that case, the value that was thrown (typically an
Error
object) is returned. You can callisError()
on the return value to determine whether an exception occurred.See also
- callWithInstance(instance[, args=QJSValueList()])¶
Calls this
QJSValue
as a function, usinginstance
as the `this’ object in the function call, and passingargs
as arguments to the function. Returns the value returned from the function.If this
QJSValue
is not a function,call()
does nothing and returns an undefinedQJSValue
.Note that if
instance
is not an object, the global object (seeglobalObject()
) will be used as the `this’ object.Calling
call()
can cause an exception to occur in the script engine; in that case,call()
returns the value that was thrown (typically anError
object). You can callisError()
on the return value to determine whether an exception occurred.See also
- deleteProperty(name)¶
- Parameters:
name – str
- Return type:
bool
Attempts to delete this object’s property of the given
name
. Returns true if the property was deleted, otherwise returns false.The behavior of this function is consistent with the JavaScript delete operator. In particular:
Non-configurable properties cannot be deleted.
This function will return true even if this object doesn’t have a property of the given
name
(i.e., non-existent properties are “trivially deletable”).If this object doesn’t have an own property of the given
name
, but an object in theprototype()
chain does, the prototype object’s property is not deleted, and this function returns true.
See also
Returns true if this
QJSValue
is equal toother
, otherwise returns false. The comparison follows the behavior described in ECMA-262 section 11.9.3, “The Abstract Equality Comparison Algorithm”.This function can return true even if the type of this
QJSValue
is different from the type of theother
value; i.e. the comparison is not strict. For example, comparing the number 9 to the string “9” returns true; comparing an undefined value to a null value returns true; comparing aNumber
object whose primitive value is 6 to aString
object whose primitive value is “6” returns true; and comparing the number 1 to the boolean valuetrue
returns true. If you want to perform a comparison without such implicit value conversion, usestrictlyEquals()
.Note that if this
QJSValue
or theother
value are objects, calling this function has side effects on the script engine, since the engine will call the object’s valueOf() function (and possiblytoString()
) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
Returns the error type this
QJSValue
represents if it is an Error object. Otherwise, returnsNoError."
See also
isError()
QJSEngine - Script Exceptions
- hasOwnProperty(name)¶
- Parameters:
name – str
- Return type:
bool
Returns true if this object has an own (not prototype-inherited) property of the given
name
, otherwise returns false.See also
- hasProperty(name)¶
- Parameters:
name – str
- Return type:
bool
Returns true if this object has a property of the given
name
, otherwise returns false.See also
- isArray()¶
- Return type:
bool
Returns true if this
QJSValue
is an object of the Array class; otherwise returns false.See also
- isBool()¶
- Return type:
bool
Returns true if this
QJSValue
is of the primitive type Boolean; otherwise returns false.See also
- isCallable()¶
- Return type:
bool
Returns true if this
QJSValue
is a function, otherwise returns false.See also
- isDate()¶
- Return type:
bool
Returns true if this
QJSValue
is an object of the Date class; otherwise returns false.- isError()¶
- Return type:
bool
Returns true if this
QJSValue
is an object of the Error class; otherwise returns false.See also
errorType()
QJSEngine - Script Exceptions
- isNull()¶
- Return type:
bool
Returns true if this
QJSValue
is of the primitive type Null; otherwise returns false.- isNumber()¶
- Return type:
bool
Returns true if this
QJSValue
is of the primitive type Number; otherwise returns false.See also
- isObject()¶
- Return type:
bool
Returns true if this
QJSValue
is of the Object type; otherwise returns false.Note that function values, variant values, and QObject values are objects, so this function returns true for such values.
See also
- isQMetaObject()¶
- Return type:
bool
Returns true if this
QJSValue
is a QMetaObject; otherwise returns false.See also
- isQObject()¶
- Return type:
bool
Returns true if this
QJSValue
is a QObject; otherwise returns false.Note: This function returns true even if the QObject that this
QJSValue
wraps has been deleted.See also
- isRegExp()¶
- Return type:
bool
Returns true if this
QJSValue
is an object of the RegExp class; otherwise returns false.- isString()¶
- Return type:
bool
Returns true if this
QJSValue
is of the primitive type String; otherwise returns false.See also
- isUndefined()¶
- Return type:
bool
Returns true if this
QJSValue
is of the primitive type Undefined or if the managed value has been cleared (by deleting the engine). Otherwise returns false.- isUrl()¶
- Return type:
bool
Returns true if this
QJSValue
is an object of the URL JavaScript class; otherwise returns false.Note
For a
QJSValue
that contains a QUrl, this function returns false. However,toVariant().value<QUrl>()
works in both cases.- isVariant()¶
- Return type:
bool
Note
This function is deprecated.
Returns true if this
QJSValue
is a variant value; otherwise returns false.Warning
This function is likely to give unexpected results. A variant value is only constructed by the
QJSEngine
in a very limited number of cases. This used to be different before Qt 5.14, wheretoScriptValue
would have created them for more types instead of corresponding ECMAScript types. You can get a valid QVariant viatoVariant
for many values for whichisVariant
returns false.See also
Returns the value of this
QJSValue
‘s property with the givenname
. If no such property exists, an undefinedQJSValue
is returned.If the property is implemented using a getter function (i.e. has the PropertyGetter flag set), calling property() has side-effects on the script engine, since the getter function will be called (possibly resulting in an uncaught script exception). If an exception occurred, property() returns the value that was thrown (typically an
Error
object).To access array elements, use the
setProperty(quint32 arrayIndex, const QJSValue &value)
overload instead.See also
- property(arrayIndex)
- Parameters:
arrayIndex – int
- Return type:
This is an overloaded function.
Returns the property at the given
arrayIndex
.It is possible to access elements in an array in two ways. The first is to use the array index as the property name:
qDebug() << jsValueArray.property(QLatin1String("4")).toString();
The second is to use the overload that takes an index:
qDebug() << jsValueArray.property(4).toString();
Both of these approaches achieve the same result, except that the latter:
Is easier to use (can use an integer directly)
Is faster (no conversion to integer)
If this
QJSValue
is not an Array object, this function behaves as ifproperty()
was called with the string representation ofarrayIndex
.If this
QJSValue
is an object, returns the internal prototype (__proto__
property) of this object; otherwise returns an undefinedQJSValue
.See also
Sets the value of this
QJSValue
‘s property with the givenname
to the givenvalue
.If this
QJSValue
is not an object, this function does nothing.If this
QJSValue
does not already have a property with namename
, a new property is created.To modify array elements, use the
setProperty(quint32 arrayIndex, const QJSValue &value)
overload instead.See also
- setProperty(arrayIndex, value)
- Parameters:
arrayIndex – int
value –
QJSValue
This is an overloaded function.
Sets the property at the given
arrayIndex
to the givenvalue
.It is possible to modify elements in an array in two ways. The first is to use the array index as the property name:
jsValueArray.setProperty(QLatin1String("4"), value);
The second is to use the overload that takes an index:
jsValueArray.setProperty(4, value);
Both of these approaches achieve the same result, except that the latter:
Is easier to use (can use an integer directly)
Is faster (no conversion to integer)
If this
QJSValue
is not an Array object, this function behaves as ifsetProperty()
was called with the string representation ofarrayIndex
.See also
property(quint32 arrayIndex)
Working With Arrays
If this
QJSValue
is an object, sets the internal prototype (__proto__
property) of this object to beprototype
; if theQJSValue
is null, it sets the prototype to null; otherwise does nothing.The internal prototype should not be confused with the public property with name “prototype”; the public prototype is usually only set on functions that act as constructors.
See also
Returns true if this
QJSValue
is equal toother
using strict comparison (no conversion), otherwise returns false. The comparison follows the behavior described in ECMA-262 section 11.9.6, “The Strict Equality Comparison Algorithm”.If the type of this
QJSValue
is different from the type of theother
value, this function returns false. If the types are equal, the result depends on the type, as shown in the following table:Type
Result
Undefined
true
Null
true
Boolean
true if both values are true, false otherwise
Number
false if either value is NaN (Not-a-Number); true if values are equal, false otherwise
String
true if both values are exactly the same sequence of characters, false otherwise
Object
true if both values refer to the same object, false otherwise
See also
- toBool()¶
- Return type:
bool
Returns the boolean value of this
QJSValue
, using the conversion rules described in ECMA-262 section 9.2, “ToBoolean”.Note that if this
QJSValue
is an object, calling this function has side effects on the script engine, since the engine will call the object’s valueOf() function (and possiblytoString()
) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
Returns a QDateTime representation of this value, in local time. If this
QJSValue
is not a date, or the value of the date is NaN (Not-a-Number), an invalid QDateTime is returned.See also
- toInt()¶
- Return type:
int
Returns the signed 32-bit integer value of this
QJSValue
, using the conversion rules described in ECMA-262 section 9.5, “ToInt32”.Note that if this
QJSValue
is an object, calling this function has side effects on the script engine, since the engine will call the object’s valueOf() function (and possiblytoString()
) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
- toNumber()¶
- Return type:
float
Returns the number value of this
QJSValue
, as defined in ECMA-262 section 9.3, “ToNumber”.Note that if this
QJSValue
is an object, calling this function has side effects on the script engine, since the engine will call the object’s valueOf() function (and possiblytoString()
) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
- toPrimitive()¶
- Return type:
Converts the value to a
QJSPrimitiveValue
. If the value holds a type supported byQJSPrimitiveValue
, the value is copied. Otherwise the value is converted to a string, and the string is stored inQJSPrimitiveValue
.Note
Conversion of a managed value to a string can throw an exception. In particular, symbols cannot be coerced into strings, or a custom
toString()
method may throw. In this case the result is the undefined value and the engine carries an error after the conversion.- toQMetaObject()¶
- Return type:
* If this
QJSValue
is a QMetaObject, returns the QMetaObject pointer * that theQJSValue
represents; otherwise, returnsNone
. * *See also
If this
QJSValue
is a QObject, returns the QObject pointer that theQJSValue
represents; otherwise, returnsNone
.If the QObject that this
QJSValue
wraps has been deleted, this function returnsNone
(i.e. it is possible for toQObject() to returnNone
even whenisQObject()
returns true).See also
- toString()¶
- Return type:
str
Returns the string value of this
QJSValue
, as defined in ECMA-262 section 9.8, “ToString”.Note that if this
QJSValue
is an object, calling this function has side effects on the script engine, since the engine will call the object’s toString() function (and possibly valueOf()) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
- toUInt()¶
- Return type:
int
Returns the unsigned 32-bit integer value of this
QJSValue
, using the conversion rules described in ECMA-262 section 9.6, “ToUint32”.Note that if this
QJSValue
is an object, calling this function has side effects on the script engine, since the engine will call the object’s valueOf() function (and possiblytoString()
) in an attempt to convert the object to a primitive value (possibly resulting in an uncaught script exception).See also
- toVariant()¶
- Return type:
object
This is an overloaded function.
Returns
toVariant
(ConvertJSObjects
).See also
- toVariant(behavior)
- Parameters:
behavior –
ObjectConversionBehavior
- Return type:
object
Returns the QVariant value of this
QJSValue
, if it can be converted to a QVariant; otherwise returns an invalid QVariant. Some JavaScript types and objects have native expressions in Qt. Those are converted to their native expressions. For example:Input Type
Result
Undefined
An invalid QVariant.
Null
A QVariant containing a null pointer (QMetaType::Nullptr).
Boolean
A QVariant containing the value of the boolean.
Number
A QVariant containing the value of the number.
String
A QVariant containing the value of the string.
QVariant Object
The result is the QVariant value of the object (no conversion).
QObject Object
A QVariant containing a pointer to the QObject.
Date Object
A QVariant containing the date value (
toDateTime()
).RegularExpression Object
A QVariant containing the regular expression value.
For other types the
behavior
parameter is relevant. IfConvertJSObjects
is given, a best effort but possibly lossy conversion is attempted. Generic JavaScript objects are converted to QVariantMap. JavaScript arrays are converted to QVariantList. Each property or element is converted to a QVariant, recursively; cyclic references are not followed. JavaScript function objects are dropped. IfRetainJSObjects
is given, theQJSValue
is wrapped into a QVariant via QVariant::fromValue(). The resulting conversion is lossless but the internal structure of the objects is not immediately accessible.See also