diff options
author | Ulf Hermann <ulf.hermann@qt.io> | 2020-12-18 16:16:52 +0100 |
---|---|---|
committer | Ulf Hermann <ulf.hermann@qt.io> | 2020-12-19 19:53:52 +0100 |
commit | 56934da44deb9ea1c2e2ad44b05285ce88592f33 (patch) | |
tree | 5481b1c9bf2e53c1d4aa7f38bd4eee14c1b66033 /src/qml/jsapi | |
parent | bf89ec173492abc679ce71f41d9e8d49a68743f3 (diff) |
QJSValue: Add a toPrimitive() method
We need a way to easily get a primitive from a QJSValue.
Change-Id: I91a55d92ffa4ba6139b1e3f2e9308800b7047563
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
Diffstat (limited to 'src/qml/jsapi')
-rw-r--r-- | src/qml/jsapi/qjsvalue.cpp | 33 | ||||
-rw-r--r-- | src/qml/jsapi/qjsvalue.h | 1 |
2 files changed, 34 insertions, 0 deletions
diff --git a/src/qml/jsapi/qjsvalue.cpp b/src/qml/jsapi/qjsvalue.cpp index 5525aee595..6d70c72722 100644 --- a/src/qml/jsapi/qjsvalue.cpp +++ b/src/qml/jsapi/qjsvalue.cpp @@ -633,6 +633,39 @@ QVariant QJSValue::toVariant(QJSValue::ObjectConversionBehavior behavior) const } /*! + * Converts the value to a QJSPrimitiveValue. If the value holds a type + * supported by QJSPrimitiveValue, the value is copied. Otherwise the + * value is converted to a string, and the string is stored in + * QJSPrimitiveValue. + * + * \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. + */ +QJSPrimitiveValue QJSValue::toPrimitive() const +{ + if (const QString *string = QJSValuePrivate::asQString(this)) + return *string; + + const QV4::Value val = QV4::Value::fromReturnedValue(QJSValuePrivate::asReturnedValue(this)); + if (val.isUndefined()) + return QJSPrimitiveUndefined(); + if (val.isNull()) + return QJSPrimitiveNull(); + if (val.isBoolean()) + return val.toBoolean(); + if (val.isInteger()) + return val.integerValue(); + if (val.isDouble()) + return val.doubleValue(); + + bool ok; + const QString result = val.toQString(&ok); + return ok ? QJSPrimitiveValue(result) : QJSPrimitiveValue(QJSPrimitiveUndefined()); +} + +/*! Calls this QJSValue as a function, passing \a args as arguments to the function, and using the globalObject() as the "this"-object. Returns the value returned from the function. diff --git a/src/qml/jsapi/qjsvalue.h b/src/qml/jsapi/qjsvalue.h index 3f8a16a149..1844ed0989 100644 --- a/src/qml/jsapi/qjsvalue.h +++ b/src/qml/jsapi/qjsvalue.h @@ -136,6 +136,7 @@ public: QVariant toVariant() const; QVariant toVariant(ObjectConversionBehavior behavior) const; + QJSPrimitiveValue toPrimitive() const; QObject *toQObject() const; const QMetaObject *toQMetaObject() const; |