- Qt 6.9
- Qt Qml
- C++ Classes
- QQmlEngine
- Qt 6.9.1 Reference Documentation

# QQmlEngine Class

The QQmlEngine class provides an environment for instantiating QML components. More...

Header: | `#include <QQmlEngine>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS Qml)` `target_link_libraries(mytarget PRIVATE Qt6::Qml)`
qmake: | `QT += qml`
Inherits: | QJSEngine
Inherited By: | QQmlApplicationEngine

- List of all members, including inherited members
- Deprecated members

## Properties

- offlineStoragePath : QString

## Public Functions

| QQmlEngine(QObject *parent = nullptr)
virtual | ~QQmlEngine() override
void | addImageProvider(const QString &providerId, QQmlImageProviderBase *provider)
void | addImportPath(const QString &path)
void | addPluginPath(const QString &path)
void | addUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
QUrl | baseUrl() const
void | clearComponentCache()
void | clearSingletons()
QQmlImageProviderBase * | imageProvider(const QString &providerId) const
QStringList | importPathList() const
QQmlIncubationController * | incubationController() const
QUrl | interceptUrl(const QUrl &url, QQmlAbstractUrlInterceptor::DataType type) const
`(since 6.6)` void | markCurrentFunctionAsTranslationBinding()
QNetworkAccessManager * | networkAccessManager() const
QQmlNetworkAccessManagerFactory * | networkAccessManagerFactory() const
QString | offlineStorageDatabaseFilePath(const QString &databaseName) const
QString | offlineStoragePath() const
bool | outputWarningsToStandardError() const
QStringList | pluginPathList() const
void | removeImageProvider(const QString &providerId)
void | removeUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
QQmlContext * | rootContext() const
void | setBaseUrl(const QUrl &url)
void | setImportPathList(const QStringList &paths)
void | setIncubationController(QQmlIncubationController *controller)
void | setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)
void | setOfflineStoragePath(const QString &dir)
void | setOutputWarningsToStandardError(bool enabled)
void | setPluginPathList(const QStringList &paths)
T | singletonInstance(int qmlTypeId)
`(since 6.5)` T | singletonInstance(QAnyStringView uri, QAnyStringView typeName)
void | trimComponentCache()
QList<QQmlAbstractUrlInterceptor *> | urlInterceptors() const

## Public Slots

void | retranslate()

## Signals

void | exit(int retCode)
`(since 6.5)` void | offlineStoragePathChanged()
void | quit()
void | warnings(const QList<QQmlError> &warnings)

## Static Public Members

QQmlContext * | contextForObject(const QObject *object)
void | setContextForObject(QObject *object, QQmlContext *context)

## Reimplemented Protected Functions

virtual bool | event(QEvent *e) override

## Related Non-Members

QQmlContext * | qmlContext(const QObject *object)
QQmlEngine * | qmlEngine(const QObject *object)

## Macros

| QML_NAMESPACE_EXTENDED(EXTENSION_NAMESPACE)

## Detailed Description

A QQmlEngine is used to manage components and objects created from them and execute their bindings and functions. QQmlEngine also inherits from QJSEngine which allows seamless integration between your QML components and JavaScript code.

Each QML component is instantiated in a QQmlContext. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QQmlEngine. By default, components are instantiated in the root context.

See also QQmlComponent, QQmlContext, QML Global Object, and QQmlApplicationEngine.

## Property Documentation

### offlineStoragePath : QString

This property holds the directory for storing offline user data

Returns the directory where SQL and other offline storage is placed.

The SQL databases created with `openDatabaseSync()` are stored here.

The default is QML/OfflineStorage in the platform-standard user application data directory.

Note that the path may not currently exist on the filesystem, so callers wanting to create new files at this location should create it first - see QDir::mkpath().

Access functions:

QString | offlineStoragePath() const
void | setOfflineStoragePath(const QString &dir)

Notifier signal:

void | offlineStoragePathChanged()

See also Qt Quick Local Storage QML Types.

## Member Function Documentation

### `[explicit]` QQmlEngine::QQmlEngine(QObject *parent = nullptr)

Create a new QQmlEngine with the given parent.

### `[override virtual noexcept]` QQmlEngine::~QQmlEngine()

Destroys the QQmlEngine.

Any QQmlContext's created on this engine will be invalidated, but not destroyed (unless they are parented to the QQmlEngine object).

See ~QJSEngine() for details on cleaning up the JS engine.

### void QQmlEngine::addImageProvider(const QString &providerId, QQmlImageProviderBase *provider)

Sets the provider to use for images requested via the image: url scheme, with host providerId. The QQmlEngine takes ownership of provider.

Image providers enable support for pixmap and threaded image requests. See the QQuickImageProvider documentation for details on implementing and using image providers.

All required image providers should be added to the engine before any QML sources files are loaded.

See also removeImageProvider(), QQuickImageProvider, and QQmlImageProviderBase.

### void QQmlEngine::addImportPath(const QString &path)

Adds path as a directory where the engine searches for installed modules in a URL-based directory structure.

The path may be a local filesystem directory, a Qt Resource path (`:/imports`), a Qt Resource url (`qrc:/imports`) or a URL.

The path will be converted into canonical form before it is added to the import path list.

The newly added path will be first in the importPathList().

See also setImportPathList(), QML Modules, and QML Import Path

### void QQmlEngine::addPluginPath(const QString &path)

Adds path as a directory where the engine searches for native plugins for imported modules (referenced in the `qmldir` file).

By default, the list contains only `.`, i.e. the engine searches in the directory of the `qmldir` file itself.

The newly added path will be first in the pluginPathList().

See also setPluginPathList().

### void QQmlEngine::addUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)

Adds a urlInterceptor to be used when resolving URLs in QML. This also applies to URLs used for loading script files and QML types. The URL interceptors should not be modifed while the engine is loading files, or URL selection may be inconsistent. Multiple URL interceptors, when given, will be called in the order they were added for each URL.

QQmlEngine does not take ownership of the interceptor and won't delete it.

### QUrl QQmlEngine::baseUrl() const

Return the base URL for this engine. The base URL is only used to resolve components when a relative URL is passed to the QQmlComponent constructor.

If a base URL has not been explicitly set, this method returns the application's current working directory.

See also setBaseUrl().

### void QQmlEngine::clearComponentCache()

Clears the engine's internal component cache.

This function causes the property metadata of most components previously loaded by the engine to be destroyed. It does so by dropping unreferenced components from the engine's component cache. It does not drop components that are still referenced since that would almost certainly lead to crashes further down the line.

If no components are referenced, this function returns the engine to a state where it does not contain any loaded component data. This may be useful in order to reload a smaller subset of the previous component set, or to load a new version of a previously loaded component.

Once the component cache has been cleared, components must be loaded before any new objects can be created.

Note: Any existing objects created from QML components retain their types, even if you clear the component cache. This includes singleton objects. If you create more objects from the same QML code after clearing the cache, the new objects will be of different types than the old ones. Assigning such a new object to a property of its declared type belonging to an object created before clearing the cache won't work.

As a general rule of thumb, make sure that no objects created from QML components are alive when you clear the component cache.

See also trimComponentCache() and clearSingletons().

### void QQmlEngine::clearSingletons()

Clears all singletons the engine owns.

This function drops all singleton instances, deleting any QObjects owned by the engine among them. This is useful to make sure that no QML-created objects are left before calling clearComponentCache().

QML properties holding QObject-based singleton instances become null if the engine owns the singleton or retain their value if the engine doesn't own it. The singletons are not automatically re-created by accessing existing QML-created objects. Only when new components are instantiated, the singletons are re-created.

See also clearComponentCache().

### `[static]` QQmlContext *QQmlEngine::contextForObject(const QObject *object)

Returns the QQmlContext for the object, or nullptr if no context has been set.

When the QQmlEngine instantiates a QObject, an internal context is assigned to it automatically. Such internal contexts are read-only. You cannot set context properties on them.

See also setContextForObject(), qmlContext(), qmlEngine(), and QQmlContext::setContextProperty().

### `[override virtual protected]` bool QQmlEngine::event(QEvent *e)

Reimplements: QObject::event(QEvent *e).

### `[signal]` void QQmlEngine::exit(int retCode)

This signal is emitted when the QML loaded by the engine would like to exit from the event loop with the specified return code retCode.

See also quit().

### QQmlImageProviderBase *QQmlEngine::imageProvider(const QString &providerId) const

Returns the image provider set for providerId if found; otherwise returns `nullptr`.

See also QQuickImageProvider.

### QStringList QQmlEngine::importPathList() const

Returns the list of directories where the engine searches for installed modules in a URL-based directory structure.

For example, if `/opt/MyApp/lib/imports` is in the path, then QML that imports `com.mycompany.Feature` will cause the QQmlEngine to look in `/opt/MyApp/lib/imports/com/mycompany/Feature/` for the components provided by that module. A `qmldir` file is required for defining the type version mapping and possibly QML extensions plugins.

By default, this list contains the paths mentioned in QML Import Path.

See also addImportPath() and setImportPathList().

### QQmlIncubationController *QQmlEngine::incubationController() const

Returns the currently set incubation controller, or 0 if no controller has been set.

See also setIncubationController().

### QUrl QQmlEngine::interceptUrl(const QUrl &url, QQmlAbstractUrlInterceptor::DataType type) const

Run the current URL interceptors on the given url of the given type and return the result.

### `[since 6.6]` void QQmlEngine::markCurrentFunctionAsTranslationBinding()

If this method is called inside of a function that is part of a binding in QML, the binding will be treated as a translation binding.

     class I18nAwareClass : public QObject {

       //...

        QString text() const
        {
             if (auto engine = qmlEngine(this))
                 engine->markCurrentFunctionAsTranslationBinding();
             return tr("Hello, world!");
        }
     };

Note: This function is mostly useful if you wish to provide your own alternative to the qsTr function. To ensure that properties exposed from C++ classes are updated on language changes, it is instead recommended to react to `LanguageChange` events. That is a more general mechanism which also works when the class is used in a non-QML context, and has slightly less overhead. However, using `markCurrentFunctionAsTranslationBinding` can be acceptable when the class is already closely tied to the QML engine. For more details, see Prepare for Dynamic Language Changes

This function was introduced in Qt 6.6.

See also QQmlEngine::retranslate.

### QNetworkAccessManager *QQmlEngine::networkAccessManager() const

Returns a common QNetworkAccessManager which can be used by any QML type instantiated by this engine.

If a QQmlNetworkAccessManagerFactory has been set and a QNetworkAccessManager has not yet been created, the QQmlNetworkAccessManagerFactory will be used to create the QNetworkAccessManager; otherwise the returned QNetworkAccessManager will have no proxy or cache set.

See also setNetworkAccessManagerFactory().

### QQmlNetworkAccessManagerFactory *QQmlEngine::networkAccessManagerFactory() const

Returns the current QQmlNetworkAccessManagerFactory.

See also setNetworkAccessManagerFactory().

### QString QQmlEngine::offlineStorageDatabaseFilePath(const QString &databaseName) const

Returns the file path where a Local Storage database with the identifier databaseName is (or would be) located.

See also LocalStorage.openDatabaseSync().

### `[signal, since 6.5]` void QQmlEngine::offlineStoragePathChanged()

This signal is emitted when offlineStoragePath changes.

Note: Notifier signal for property offlineStoragePath.

This function was introduced in Qt 6.5.

### bool QQmlEngine::outputWarningsToStandardError() const

Returns true if warning messages will be output to stderr in addition to being emitted by the warnings() signal, otherwise false.

The default value is true.

See also setOutputWarningsToStandardError().

### QStringList QQmlEngine::pluginPathList() const

Returns the list of directories where the engine searches for native plugins for imported modules (referenced in the `qmldir` file).

By default, the list contains only `.`, i.e. the engine searches in the directory of the `qmldir` file itself.

See also addPluginPath() and setPluginPathList().

### `[signal]` void QQmlEngine::quit()

This signal is emitted when the QML loaded by the engine would like to quit.

See also exit().

### void QQmlEngine::removeImageProvider(const QString &providerId)

Removes the image provider for providerId.

See also addImageProvider() and QQuickImageProvider.

### void QQmlEngine::removeUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)

Remove a urlInterceptor that was previously added using addUrlInterceptor. The URL interceptors should not be modifed while the engine is loading files, or URL selection may be inconsistent.

This does not delete the interceptor, but merely removes it from the engine. You can re-use it on the same or a different engine afterwards.

### `[slot]` void QQmlEngine::retranslate()

Refreshes all binding expressions that use strings marked for translation.

Call this function after you have installed a new translator with QCoreApplication::installTranslator, to ensure that your user-interface shows up-to-date translations.

### QQmlContext *QQmlEngine::rootContext() const

Returns the engine's root context.

The root context is automatically created by the QQmlEngine. Data that should be available to all QML component instances instantiated by the engine should be put in the root context.

Additional data that should only be available to a subset of component instances should be added to sub-contexts parented to the root context.

### void QQmlEngine::setBaseUrl(const QUrl &url)

Set the base URL for this engine to url.

See also baseUrl().

### `[static]` void QQmlEngine::setContextForObject(QObject *object, QQmlContext *context)

Sets the QQmlContext for the object to context. If the object already has a context, a warning is output, but the context is not changed.

When the QQmlEngine instantiates a QObject, the context is set automatically.

See also contextForObject().

### void QQmlEngine::setImportPathList(const QStringList &paths)

Sets paths as the list of directories where the engine searches for installed modules in a URL-based directory structure.

By default, this list contains the paths mentioned in QML Import Path.

Warning: Calling setImportPathList does not preserve the default import paths.

See also importPathList() and addImportPath().

### void QQmlEngine::setIncubationController(QQmlIncubationController *controller)

Sets the engine's incubation controller. The engine can only have one active controller and it does not take ownership of it.

See also incubationController().

### void QQmlEngine::setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)

Sets the factory to use for creating QNetworkAccessManager(s).

QNetworkAccessManager is used for all network access by QML. By implementing a factory it is possible to create custom QNetworkAccessManager with specialized caching, proxy and cookie support.

The factory must be set before executing the engine.

Note: QQmlEngine does not take ownership of the factory.

See also networkAccessManagerFactory().

### void QQmlEngine::setOutputWarningsToStandardError(bool enabled)

Set whether warning messages will be output to stderr to enabled.

If enabled is true, any warning messages generated by QML will be output to stderr and emitted by the warnings() signal. If enabled is false, only the warnings() signal will be emitted. This allows applications to handle warning output themselves.

The default value is true.

See also outputWarningsToStandardError().

### void QQmlEngine::setPluginPathList(const QStringList &paths)

Sets the list of directories where the engine searches for native plugins for imported modules (referenced in the `qmldir` file) to paths.

By default, the list contains only `.`, i.e. the engine searches in the directory of the `qmldir` file itself.

See also pluginPathList() and addPluginPath().

### template <typename T> T QQmlEngine::singletonInstance(int qmlTypeId)

Returns the instance of a singleton type that was registered under qmlTypeId.

The template argument T may be either QJSValue or a pointer to a QObject-derived type and depends on how the singleton was registered. If no instance of T has been created yet, it is created now. If qmlTypeId does not represent a valid singleton type, either a default constructed QJSValue or a `nullptr` is returned.

QObject* example:

     class MySingleton : public QObject {
         Q_OBJECT

         // Register as default constructed singleton.
         QML_ELEMENT
         QML_SINGLETON

         static int typeId;
         // ...
     };

         MySingleton::typeId = qmlTypeId(...);

         // Retrieve as QObject*
         QQmlEngine engine;
         MySingleton* instance = engine.singletonInstance<MySingleton*>(MySingleton::typeId);

QJSValue example:

         // Register with QJSValue callback
         int typeId = qmlRegisterSingletonType(...);

         // Retrieve as QJSValue
         QQmlEngine engine;
         QJSValue instance = engine.singletonInstance<QJSValue>(typeId);

It is recommended to store the QML type id, e.g. as a static member in the singleton class. The lookup via qmlTypeId() is costly.

See also QML_SINGLETON, qmlRegisterSingletonType(), and qmlTypeId().

### `[since 6.5]` template <typename T> T QQmlEngine::singletonInstance(QAnyStringView uri, QAnyStringView typeName)

This is an overloaded function.

Returns the instance of a singleton type named typeName from the module specified by uri.

This method can be used as an alternative to calling qmlTypeId followed by the id based overload of singletonInstance. This is convenient when one only needs to do a one time setup of a singleton; if repeated access to the singleton is required, caching its typeId will allow faster subsequent access via the type-id based overload.

The template argument T may be either QJSValue or a pointer to a QObject-derived type and depends on how the singleton was registered. If no instance of T has been created yet, it is created now. If typeName does not represent a valid singleton type, either a default constructed QJSValue or a `nullptr` is returned.

         QQmlEngine engine;
         MySingleton *singleton = engine.singletonInstance<MySingleton *>("mymodule", "MySingleton");
     /

This function was introduced in Qt 6.5.

See also QML_SINGLETON, qmlRegisterSingletonType(), and qmlTypeId().

### void QQmlEngine::trimComponentCache()

Trims the engine's internal component cache.

This function causes the property metadata of any loaded components which are not currently in use to be destroyed.

A component is considered to be in use if there are any extant instances of the component itself, any instances of other components that use the component, or any objects instantiated by any of those components.

See also clearComponentCache().

### QList<QQmlAbstractUrlInterceptor *> QQmlEngine::urlInterceptors() const

Returns the list of currently active URL interceptors.

### `[signal]` void QQmlEngine::warnings(const QList<QQmlError> &warnings)

This signal is emitted when warnings messages are generated by QML.

## Related Non-Members

### QQmlContext *qmlContext(const QObject *object)

Returns the QQmlContext associated with object, if any. This is equivalent to QQmlEngine::contextForObject(object).

Note: Add `#include <QtQml>` to use this function.

See also contextForObject() and qmlEngine().

### QQmlEngine *qmlEngine(const QObject *object)

Returns the QQmlEngine associated with object, if any. This is equivalent to QQmlEngine::contextForObject(object)->engine(), but more efficient.

Note: Add `#include <QtQml>` to use this function.

See also contextForObject() and qmlContext().

## Macro Documentation

### QML_NAMESPACE_EXTENDED(EXTENSION_NAMESPACE)

Behaves the same way as QML_EXTENDED_NAMESPACE with the distinction that what is being extended is a namespace and not a type.

Declares that the enclosing namespace uses EXTENSION_NAMESPACE as an extension to provide further enumerations in QML. This takes effect if the extended namespace is exposed to QML using a QML_ELEMENT or QML_NAMED_ELEMENT() macro. The enumerations need to be exposed to the metaobject system for this to work.

For example, in the following C++ code,

     namespace NS2 {
         Q_NAMESPACE

         enum class E2 { D = 3, E, F };
         Q_ENUM_NS(E2)
     }

     namespace NS1 {
         Q_NAMESPACE
         QML_ELEMENT

         enum class E1 { A, B, C };
         Q_ENUM_NS(E1)

         // Extends NS1 with NS2
         QML_NAMESPACE_EXTENDED(NS2)
     }

the namespace `NS1` is extended with `NS2` and the `E2` enum becomes available within `NS1` from QML.

     Item {
         Component.onCompleted: console.log(NS1.E1.A, NS1.E2.D)
     }

Note: EXTENSION_NAMESPACE can also be a QObject or QGadget; in that case - and in contrast to QML_EXTENDED, which also exposes methods and properties - only its enumerations are exposed.

Note: EXTENSION_NAMESPACE must have a metaobject; i.e. it must either be a namespace which contains the Q_NAMESPACE macro or a QObject/QGadget.

Note: The class name needs to be fully qualified, even if you're already inside the namespace.

See also QML_EXTENDED_NAMESPACE(), QML_ELEMENT, QML_NAMED_ELEMENT(), QML_EXTENDED(), Registering Extension Objects, Q_ENUM, and Q_ENUM_NS.