Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
QJSEngine Class Reference

The QJSEngine class provides an environment for evaluating JavaScript code. More...

#include <qjsengine.h>

+ Inheritance diagram for QJSEngine:
+ Collaboration diagram for QJSEngine:

Public Types

enum  ObjectOwnership { CppOwnership , JavaScriptOwnership }
 ObjectOwnership controls whether or not the JavaScript memory manager automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine. More...
 
enum  Extension { TranslationExtension = 0x1 , ConsoleExtension = 0x2 , GarbageCollectionExtension = 0x4 , AllExtensions = 0xffffffff }
 This enum is used to specify extensions to be installed via \l installExtensions(). More...
 

Signals

void uiLanguageChanged ()
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 

Public Member Functions

 QJSEngine ()
 Constructs a QJSEngine object.
 
 QJSEngine (QObject *parent)
 Constructs a QJSEngine object with the given parent.
 
 ~QJSEngine () override
 Destroys this QJSEngine.
 
QJSValue globalObject () const
 Returns this engine's Global Object.
 
QJSValue evaluate (const QString &program, const QString &fileName=QString(), int lineNumber=1, QStringList *exceptionStackTrace=nullptr)
 Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation.
 
QJSValue importModule (const QString &fileName)
 Imports the module located at fileName and returns a module namespace object that contains all exported variables, constants and functions as properties.
 
bool registerModule (const QString &moduleName, const QJSValue &value)
 Registers a QJSValue to serve as a module.
 
QJSValue newObject ()
 Creates a JavaScript object of class Object.
 
QJSValue newSymbol (const QString &name)
 
QJSValue newArray (uint length=0)
 Creates a JavaScript object of class Array with the given length.
 
QJSValue newQObject (QObject *object)
 Creates a JavaScript object that wraps the given QObject object, using JavaScriptOwnership.
 
QJSValue newQMetaObject (const QMetaObject *metaObject)
 
template<typename T >
QJSValue newQMetaObject ()
 
QJSValue newErrorObject (QJSValue::ErrorType errorType, const QString &message=QString())
 
template<typename T >
QJSValue toScriptValue (const T &value)
 Creates a QJSValue with the given value.
 
template<typename T >
QJSManagedValue toManagedValue (const T &value)
 Creates a QJSManagedValue with the given value.
 
template<typename T >
QJSPrimitiveValue toPrimitiveValue (const T &value)
 Creates a QJSPrimitiveValue with the given value.
 
template<typename T >
fromScriptValue (const QJSValue &value)
 Returns the given value converted to the template type {T}.
 
template<typename T >
fromManagedValue (const QJSManagedValue &value)
 Returns the given value converted to the template type {T}.
 
template<typename T >
fromPrimitiveValue (const QJSPrimitiveValue &value)
 Returns the given value converted to the template type {T}.
 
template<typename T >
fromVariant (const QVariant &value)
 Returns the given value converted to the template type {T}.
 
template<typename From , typename To >
To coerceValue (const From &from)
 Returns the given from converted to the template type {To}.
 
void collectGarbage ()
 Runs the garbage collector.
 
void installExtensions (Extensions extensions, const QJSValue &object=QJSValue())
 
void setInterrupted (bool interrupted)
 
bool isInterrupted () const
 
QV4::ExecutionEnginehandle () const
 
void throwError (const QString &message)
 Throws a run-time error (exception) with the given message.
 
void throwError (QJSValue::ErrorType errorType, const QString &message=QString())
 
void throwError (const QJSValue &error)
 
bool hasError () const
 Returns true if the last JavaScript execution resulted in an exception or if throwError() was called.
 
QJSValue catchError ()
 If an exception is currently pending, catches it and returns it as a QJSValue.
 
QString uiLanguage () const
 
void setUiLanguage (const QString &language)
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool event (QEvent *event)
 This virtual function receives events to an object and should return true if the event e was recognized and processed.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Static Public Member Functions

static void setObjectOwnership (QObject *, ObjectOwnership)
 Sets the ownership of object.
 
static ObjectOwnership objectOwnership (QObject *)
 Returns the ownership of object.
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 

Protected Member Functions

 QJSEngine (QJSEnginePrivate &dd, QObject *parent=nullptr)
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 

Properties

QString uiLanguage
 the language to be used for translating user interface strings
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Friends

template<typename T >
qjsvalue_cast (const QJSValue &value)
 
template<typename T >
qjsvalue_cast (const QJSManagedValue &value)
 
template<typename T >
qjsvalue_cast (const QJSPrimitiveValue &value)
 

Related Symbols

(Note that these are not member symbols.)

QJSEngineqjsEngine (const QObject *object)
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 
- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 

Detailed Description

The QJSEngine class provides an environment for evaluating JavaScript code.

Since
5.0

\reentrant

\inmodule QtQml

Definition at line 24 of file qjsengine.h.

Member Enumeration Documentation

◆ Extension

This enum is used to specify extensions to be installed via \l installExtensions().

\value TranslationExtension Indicates that translation functions (qsTr(), for example) should be installed. This also installs the Qt.uiLanguage property.

\value ConsoleExtension Indicates that console functions (console.log(), for example) should be installed.

\value GarbageCollectionExtension Indicates that garbage collection functions (gc(), for example) should be installed.

\value AllExtensions Indicates that all extension should be installed.

TranslationExtension

The relation between script translation functions and C++ translation functions is described in the following table:

\table \header

This flag also adds an arg() function to the string prototype.

For more information, see the \l {Internationalization with Qt} documentation.

ConsoleExtension

The \l {Console API}{console} object implements a subset of the \l {https://developer.mozilla.org/en-US/docs/Web/API/Console}{Console API}, which provides familiar logging functions, such as console.log().

The list of functions added is as follows:

\list

  • console.assert()
  • console.debug()
  • console.exception()
  • console.info()
  • console.log() (equivalent to console.debug())
  • console.error()
  • console.time()
  • console.timeEnd()
  • console.trace()
  • console.count()
  • console.warn()
  • {print()} (equivalent to console.debug()) \endlist

For more information, see the \l {Console API} documentation.

GarbageCollectionExtension

The gc() function is equivalent to calling \l collectGarbage().

Enumerator
TranslationExtension 
ConsoleExtension 
GarbageCollectionExtension 
AllExtensions 

Definition at line 285 of file qjsengine.h.

◆ ObjectOwnership

ObjectOwnership controls whether or not the JavaScript memory manager automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine.

The two ownership options are:

\value CppOwnership The object is owned by C++ code and the JavaScript memory manager will never delete it. The JavaScript destroy() method cannot be used on these objects. This option is similar to QScriptEngine::QtOwnership.

\value JavaScriptOwnership The object is owned by JavaScript. When the object is returned to the JavaScript memory manager as the return value of a method call, the JavaScript memory manager will track it and delete it if there are no remaining JavaScript references to it and it has no QObject::parent(). An object tracked by one QJSEngine will be deleted during that QJSEngine's destructor. Thus, JavaScript references between objects with JavaScriptOwnership from two different engines will not be valid if one of these engines is deleted. This option is similar to QScriptEngine::ScriptOwnership.

Generally an application doesn't need to set an object's ownership explicitly. The JavaScript memory manager uses a heuristic to set the default ownership. By default, an object that is created by the JavaScript memory manager has JavaScriptOwnership. The exception to this are the root objects created by calling QQmlComponent::create() or QQmlComponent::beginCreate(), which have CppOwnership by default. The ownership of these root-level objects is considered to have been transferred to the C++ caller.

Objects not-created by the JavaScript memory manager have CppOwnership by default. The exception to this are objects returned from C++ method calls; their ownership will be set to JavaScriptOwnership. This applies only to explicit invocations of Q_INVOKABLE methods or slots, but not to property getter invocations.

Calling setObjectOwnership() overrides the default ownership.

See also
{Data Ownership}
Enumerator
CppOwnership 
JavaScriptOwnership 

Definition at line 281 of file qjsengine.h.

Constructor & Destructor Documentation

◆ QJSEngine() [1/3]

QJSEngine::QJSEngine ( )

Constructs a QJSEngine object.

The globalObject() is initialized to have properties as described in \l{ECMA-262}, Section 15.1.

Definition at line 336 of file qjsengine.cpp.

◆ QJSEngine() [2/3]

QJSEngine::QJSEngine ( QObject * parent)
explicit

Constructs a QJSEngine object with the given parent.

The globalObject() is initialized to have properties as described in \l{ECMA-262}, Section 15.1.

Definition at line 348 of file qjsengine.cpp.

◆ ~QJSEngine()

QJSEngine::~QJSEngine ( )
override

Destroys this QJSEngine.

Garbage is not collected from the persistent JS heap during QJSEngine destruction. If you need all memory freed, call collectGarbage() manually right before destroying the QJSEngine.

Definition at line 371 of file qjsengine.cpp.

◆ QJSEngine() [3/3]

QJSEngine::QJSEngine ( QJSEnginePrivate & dd,
QObject * parent = nullptr )
protected

Definition at line 357 of file qjsengine.cpp.

Member Function Documentation

◆ catchError()

QJSValue QJSEngine::catchError ( )

If an exception is currently pending, catches it and returns it as a QJSValue.

Otherwise returns undefined as QJSValue. After calling this method hasError() returns false.

Since
Qt 6.1

Definition at line 1188 of file qjsengine.cpp.

◆ coerceValue()

template<typename From , typename To >
To QJSEngine::coerceValue ( const From & from)
inline

Returns the given from converted to the template type {To}.

The conversion is done in JavaScript semantics. Those differ from qvariant_cast's semantics. There are a number of implicit conversions between JavaScript-equivalent types that are not performed by qvariant_cast by default. This method is a generalization of all the other conversion methods in this class.

See also
fromVariant(), {QVariant::}{qvariant_cast()}, fromScriptValue(), toScriptValue()

Definition at line 185 of file qjsengine.h.

◆ collectGarbage()

void QJSEngine::collectGarbage ( )

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 QJSEngine 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 also
{Garbage Collection}
{Qt::}{gc()}

Definition at line 398 of file qjsengine.cpp.

◆ evaluate()

QJSValue QJSEngine::evaluate ( const QString & program,
const QString & fileName = QString(),
int lineNumber = 1,
QStringList * exceptionStackTrace = nullptr )

Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation.

The script code will be evaluated in the context of the global object.

Note
If you need to evaluate inside a QML context, use \l QQmlExpression instead.

The evaluation of program can cause an \l{Script Exceptions}{exception} in the engine; in this case the return value will be the exception that was thrown (typically an {Error} object; see QJSValue::isError()).

lineNumber is used to specify a starting line number for program; line number information reported by the engine that pertains to this evaluation 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, the exception line number would be 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 is provided with this function.

exceptionStackTrace is used to report whether an uncaught exception was thrown. If you pass a non-null pointer to a QStringList to it, it will set it to list of "stackframe messages" if the script threw an unhandled exception, or an empty list otherwise. A stackframe message has the format function name:line number:column:file name

Note
In some cases, e.g. for native functions, function name and file name can be empty and line number and column can be -1.
If an exception was thrown and the exception value is not an Error instance (i.e., QJSValue::isError() returns false), the exception value will still be returned. Use exceptionStackTrace->isEmpty() to distinguish whether the value was a normal or an exceptional return value.
See also
QQmlExpression::evaluate

Definition at line 516 of file qjsengine.cpp.

◆ fromManagedValue()

template<typename T >
T QJSEngine::fromManagedValue ( const QJSManagedValue & value)
inline

Returns the given value converted to the template type {T}.

See also
toManagedValue(), coerceValue()

Definition at line 91 of file qjsengine.h.

◆ fromPrimitiveValue()

template<typename T >
T QJSEngine::fromPrimitiveValue ( const QJSPrimitiveValue & value)
inline

Returns the given value converted to the template type {T}.

Since QJSPrimitiveValue can only hold int, bool, double, QString, and the equivalents of JavaScript null and undefined, the value will be coerced aggressively if you request any other type.

See also
toPrimitiveValue(), coerceValue()

Definition at line 97 of file qjsengine.h.

◆ fromScriptValue()

template<typename T >
T QJSEngine::fromScriptValue ( const QJSValue & value)
inline

Returns the given value converted to the template type {T}.

See also
toScriptValue(), coerceValue()

Definition at line 85 of file qjsengine.h.

◆ fromVariant()

template<typename T >
T QJSEngine::fromVariant ( const QVariant & value)
inline

Returns the given value converted to the template type {T}.

The conversion is done in JavaScript semantics. Those differ from qvariant_cast's semantics. There are a number of implicit conversions between JavaScript-equivalent types that are not performed by qvariant_cast by default.

See also
coerceValue(), fromScriptValue(), {QVariant::}{qvariant_cast()}

Definition at line 115 of file qjsengine.h.

◆ globalObject()

QJSValue QJSEngine::globalObject ( ) const

Returns this engine's Global Object.

By default, the Global Object contains the built-in objects that are part of \l{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.

Definition at line 797 of file qjsengine.cpp.

◆ handle()

QV4::ExecutionEngine * QJSEngine::handle ( ) const
inline

Definition at line 298 of file qjsengine.h.

◆ hasError()

bool QJSEngine::hasError ( ) const

Returns true if the last JavaScript execution resulted in an exception or if throwError() was called.

Otherwise returns false. Mind that evaluate() catches any exceptions thrown in the evaluated code.

Since
Qt 6.1

Definition at line 1176 of file qjsengine.cpp.

◆ importModule()

QJSValue QJSEngine::importModule ( const QString & fileName)

Imports the module located at fileName and returns a module namespace object that contains all exported variables, constants and functions as properties.

If this is the first time the module is imported in the engine, the file is loaded from the specified location in either the local file system or the Qt resource system and evaluated as an ECMAScript module. The file is expected to be encoded in UTF-8 text.

Subsequent imports of the same module will return the previously imported instance. Modules are singletons and remain around until the engine is destroyed.

The specified fileName will internally be normalized using \l QFileInfo::canonicalFilePath(). That means that multiple imports of the same file on disk using different relative paths will load the file only once.

Note
If an exception is thrown during the loading of the module, the return value will be the exception (typically an {Error} object; see QJSValue::isError()).
See also
registerModule()
Since
5.12

Definition at line 575 of file qjsengine.cpp.

◆ installExtensions()

void QJSEngine::installExtensions ( Extensions extensions,
const QJSValue & object = QJSValue() )
Since
5.6

Installs JavaScript extensions to add functionality that is not available in a standard ECMAScript implementation.

The extensions are installed on the given object, or on the \l {globalObject()}{Global Object} if no object is specified.

Several extensions can be installed at once by {OR}-ing the enum values:

void installExtensions(Extensions extensions, const QJSValue &object=QJSValue())
@ ConsoleExtension
Definition qjsengine.h:287
@ TranslationExtension
Definition qjsengine.h:286
See also
Extension

Definition at line 420 of file qjsengine.cpp.

◆ isInterrupted()

bool QJSEngine::isInterrupted ( ) const
Since
5.14 Returns whether JavaScript execution is currently interrupted.
See also
setInterrupted()

Definition at line 458 of file qjsengine.cpp.

◆ newArray()

QJSValue QJSEngine::newArray ( uint length = 0)

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

See also
newObject()

Definition at line 713 of file qjsengine.cpp.

◆ newErrorObject()

QJSValue QJSEngine::newErrorObject ( QJSValue::ErrorType errorType,
const QString & message = QString() )
Since
5.12

Creates a JavaScript object of class Error, with message as the error message.

The prototype of the created object will be errorType.

See also
newObject(), throwError(), QJSValue::isError()

Definition at line 676 of file qjsengine.cpp.

◆ newObject()

QJSValue QJSEngine::newObject ( )

Creates a JavaScript object of class Object.

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

See also
newArray(), QJSValue::setProperty()

Definition at line 643 of file qjsengine.cpp.

◆ newQMetaObject() [1/2]

template<typename T >
QJSValue QJSEngine::newQMetaObject ( )
inline
Since
5.8 Creates a JavaScript object that wraps the static QMetaObject associated with class {T}.
See also
newQObject(), {QObject Integration}

Definition at line 50 of file qjsengine.h.

◆ newQMetaObject() [2/2]

QJSValue QJSEngine::newQMetaObject ( const QMetaObject * metaObject)
Since
5.8

Creates a JavaScript object that wraps the given QMetaObject The metaObject must outlive the script engine. It is recommended to only use this method with static metaobjects.

When called as a constructor, a new instance of the class will be created. Only constructors exposed by Q_INVOKABLE will be visible from the script engine.

See also
newQObject(), {QObject Integration}

Definition at line 770 of file qjsengine.cpp.

◆ newQObject()

QJSValue QJSEngine::newQObject ( QObject * object)

Creates a JavaScript object that wraps the given QObject object, using JavaScriptOwnership.

Signals and slots, properties and children of object are available as properties of the created QJSValue.

If object is a null pointer, this function returns a null value.

If a default prototype has been registered for the object's class (or its superclass, recursively), the prototype of the new script object will be set to be that default prototype.

If the given object is deleted outside of the engine's control, any attempt to access the deleted QObject's members through the JavaScript wrapper object (either by script code or C++) will result in a \l{Script Exceptions}{script exception}.

See also
QJSValue::toQObject()

Definition at line 743 of file qjsengine.cpp.

◆ newSymbol()

QJSValue QJSEngine::newSymbol ( const QString & name)
Since
6.2

Creates a JavaScript object of class Symbol, with value name.

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

See also
newObject()

Definition at line 659 of file qjsengine.cpp.

◆ objectOwnership()

QJSEngine::ObjectOwnership QJSEngine::objectOwnership ( QObject * object)
static

Returns the ownership of object.

See also
QJSEngine::ObjectOwnership

Definition at line 1332 of file qjsengine.cpp.

◆ registerModule()

bool QJSEngine::registerModule ( const QString & moduleName,
const QJSValue & value )

Registers a QJSValue to serve as a module.

After this function is called, all modules that import moduleName will import the value of value instead of loading moduleName from the filesystem.

Any valid QJSValue can be registered, but named exports (i.e. {import { name } from "info"} are treated as members of an object, so the default export must be created with one of the newXYZ methods of QJSEngine.

Because this allows modules that do not exist on the filesystem to be imported, scripting applications can use this to provide built-in modules, similar to Node.js.

Returns true on success, false otherwise.

Note
The QJSValue value is not called or read until it is used by another module. This means that there is no code to evaluate, so no errors will be seen until another module throws an exception while trying to load this module.
Warning
Attempting to access a named export from a QJSValue that is not an object will trigger a \l{Script Exceptions}{exception}.
See also
importModule()

Definition at line 625 of file qjsengine.cpp.

◆ setInterrupted()

void QJSEngine::setInterrupted ( bool interrupted)
Since
5.14 Interrupts or re-enables JavaScript execution.

If interrupted is true, any JavaScript executed by this engine immediately aborts and returns an error object until this function is called again with a value of false for interrupted.

This function is thread safe. You may call it from a different thread in order to interrupt, for example, an infinite loop in JavaScript.

Definition at line 447 of file qjsengine.cpp.

◆ setObjectOwnership()

void QJSEngine::setObjectOwnership ( QObject * object,
ObjectOwnership ownership )
static

Sets the ownership of object.

An object with JavaScriptOwnership is not garbage collected as long as it still has a parent, even if there are no references to it.

See also
QJSEngine::ObjectOwnership

Definition at line 1314 of file qjsengine.cpp.

◆ setUiLanguage()

void QJSEngine::setUiLanguage ( const QString & language)

Definition at line 1210 of file qjsengine.cpp.

◆ throwError() [1/3]

void QJSEngine::throwError ( const QJSValue & error)

Definition at line 1164 of file qjsengine.cpp.

◆ throwError() [2/3]

void QJSEngine::throwError ( const QString & message)

Throws a run-time error (exception) with the given message.

This method is the C++ counterpart of a throw() expression in JavaScript. It enables C++ code to report run-time errors to QJSEngine. Therefore it should only be called from C++ code that was invoked by a JavaScript function through QJSEngine.

When returning from C++, the engine will interrupt the normal flow of execution and call the next pre-registered exception handler with an error object that contains the given message. The error object will point to the location of the top-most context on the JavaScript caller stack; specifically, it will have properties lineNumber, fileName and stack. These properties are described in \l{Script Exceptions}.

In the following example a C++ method in FileAccess.cpp throws an error in qmlFile.qml at the position where readFileAsText() is called:

// qmlFile.qml
function someFunction() {
...
var text = FileAccess.readFileAsText("/path/to/file.txt");
}
QString text
[12]
// FileAccess.cpp
// Assuming that FileAccess is a QObject-derived class that has been
// registered as a singleton type and provides an invokable method
// readFileAsText()
QJSValue FileAccess::readFileAsText(const QString & filePath) {
QFile file(filePath);
jsEngine->throwError(file.errorString());
return QString();
}
...
return content;
}
\inmodule QtCore
Definition qfile.h:93
QFILE_MAYBE_NODISCARD bool open(OpenMode flags) override
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition qfile.cpp:925
QString errorString() const
Returns a human-readable description of the last device error that occurred.
The QJSValue class acts as a container for Qt/JavaScript data types.
Definition qjsvalue.h:31
QFile file
[0]

It is also possible to catch the thrown error in JavaScript:

// qmlFile.qml
function someFunction() {
...
try {
text = FileAccess.readFileAsText("/path/to/file.txt");
} catch (error) {
console.warn("In " + error.fileName + ":" + "error.lineNumber" +
": " + error.message);
}
}
DBusConnection const char DBusError * error
const char * message

If you need a more specific run-time error to describe an exception, you can use the \l {QJSEngine::}{throwError(QJSValue::ErrorType errorType, const QString &message)} overload.

Since
Qt 5.12
See also
{Script Exceptions}

Definition at line 1117 of file qjsengine.cpp.

◆ throwError() [3/3]

void QJSEngine::throwError ( QJSValue::ErrorType errorType,
const QString & message = QString() )

Definition at line 1145 of file qjsengine.cpp.

◆ toManagedValue()

template<typename T >
QJSManagedValue QJSEngine::toManagedValue ( const T & value)
inline

Creates a QJSManagedValue with the given value.

See also
fromManagedValue(), coerceValue()

Definition at line 64 of file qjsengine.h.

◆ toPrimitiveValue()

template<typename T >
QJSPrimitiveValue QJSEngine::toPrimitiveValue ( const T & value)
inline

Creates a QJSPrimitiveValue with the given value.

Since QJSPrimitiveValue can only hold int, bool, double, QString, and the equivalents of JavaScript null and undefined, the value will be coerced aggressively if you pass any other type.

See also
fromPrimitiveValue(), coerceValue()

Definition at line 70 of file qjsengine.h.

◆ toScriptValue()

template<typename T >
QJSValue QJSEngine::toScriptValue ( const T & value)
inline

Creates a QJSValue with the given value.

See also
fromScriptValue(), coerceValue()

Definition at line 58 of file qjsengine.h.

◆ uiLanguage()

QString QJSEngine::uiLanguage ( ) const

Definition at line 1215 of file qjsengine.cpp.

◆ uiLanguageChanged

void QJSEngine::uiLanguageChanged ( )
signal

Friends And Related Symbol Documentation

◆ qjsEngine()

QJSEngine * qjsEngine ( const QObject * object)
related
Since
5.5

Returns the QJSEngine associated with object, if any.

This function is useful if you have exposed a QObject to the JavaScript environment and later in your program would like to regain access. It does not require you to keep the wrapper around that was returned from QJSEngine::newQObject().

Definition at line 1261 of file qjsengine.cpp.

◆ qjsvalue_cast [1/3]

template<typename T >
T qjsvalue_cast ( const QJSManagedValue & value)
friend

Definition at line 366 of file qjsengine.h.

◆ qjsvalue_cast [2/3]

template<typename T >
T qjsvalue_cast ( const QJSPrimitiveValue & value)
friend

Definition at line 375 of file qjsengine.h.

◆ qjsvalue_cast [3/3]

template<typename T >
T qjsvalue_cast ( const QJSValue & value)
friend

Definition at line 358 of file qjsengine.h.

Property Documentation

◆ uiLanguage

QString QJSEngine::uiLanguage
readwrite

the language to be used for translating user interface strings

Since
5.15

This property holds the name of the language to be used for user interface string translations. It is exposed for reading and writing as {Qt.uiLanguage} when the QJSEngine::TranslationExtension is installed on the engine. It is always exposed in instances of QQmlEngine.

You can set the value freely and use it in bindings. It is recommended to set it after installing translators in your application. By convention, an empty string means no translation from the language used in the source code is intended to occur.

Definition at line 28 of file qjsengine.h.


The documentation for this class was generated from the following files: