QQmlEngine Class

Detailed Description

Each QML component is instantiated in a QQmlContext. QQmlContext's are essential for passing data to QML components. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QQmlEngine.

Prior to creating any QML components, an application must have created a QQmlEngine to gain access to a QML context. The following example shows how to create a simple Text item.

 
Sélectionnez
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: \"Hello world!\" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());

//add item to view, etc
...

In this case, the Text item will be created in the engine's root context.

See Also

Member Type Documentation

 

enum QQmlEngine::ObjectOwnership

ObjectOwnership controls whether or not QML automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine. The two ownership options are:

Constant

Value

Description

QQmlEngine::CppOwnership

0

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

QQmlEngine::JavaScriptOwnership

1

The object is owned by JavaScript. When the object is returned to QML as the return value of a method call, QML 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 QQmlEngine will be deleted during that QQmlEngine'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. QML uses a heuristic to set the default ownership. By default, an object that is created by QML 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 QML 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 heuristic used by QML.

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 openDatabase() 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:

  • offlineStoragePath() const

  • void setOfflineStoragePath(const &dir)

Member Function Documentation

 

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

Create a new QQmlEngine with the given parent.

[override virtual] 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 docs 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

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

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

See also setPluginPathList()

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

See also setBaseUrl()

void QQmlEngine::clearComponentCache()

Clears the engine's internal component cache.

This function causes the property metadata of all components previously loaded by the engine to be destroyed. All previously loaded components and the property bindings for all extant objects created from those components will cease to function.

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.

See Also

See also trimComponentCache()

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

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

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

See Also

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

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

[since 5.8] 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.

This function was introduced in Qt 5.8.

See Also

See also quit()

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

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

See Also

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, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo.

See Also

bool QQmlEngine::importPlugin(const QString &filePath, const QString &uri, QList<QQmlError> *errors)

Imports the plugin named filePath with the uri provided. Returns true if the plugin was successfully imported; otherwise returns false.

On failure and if non-null, the errors list will have any errors which occurred prepended to it.

The plugin has to be a Qt plugin which implements the QQmlExtensionPlugin interface.

QQmlIncubationController *QQmlEngine::incubationController() const

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

See Also

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

QQmlNetworkAccessManagerFactory *QQmlEngine::networkAccessManagerFactory() const

Returns the current QQmlNetworkAccessManagerFactory.

See Also

[static] QQmlEngine::ObjectOwnership QQmlEngine::objectOwnership(QObject *object)

Returns the ownership of object.

See Also

See also setObjectOwnership()

[since 5.9] 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.

This function was introduced in Qt 5.9.

See Also

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

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

void QQmlEngine::quit()

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

See Also

See also exit()

void QQmlEngine::removeImageProvider(const QString &providerId)

Removes the image provider for providerId.

See Also

[since 5.10] 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.

Due to a limitation in the implementation, this function refreshes all the engine's bindings, not only those that use strings marked for translation. This may be optimized in a future release.

This function was introduced in Qt 5.10.

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

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

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, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo.

See Also

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

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.

QQmlEngine does not take ownership of the factory.

See Also

[static] void QQmlEngine::setObjectOwnership(QObject *object, QQmlEngine::ObjectOwnership ownership)

Sets the ownership of object.

See Also

See also objectOwnership()

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

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

[since 5.12] 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:

 
Sélectionnez
class MySingleton : public QObject {
  Q_OBJECT
  static int typeId;
  // ...
};

// Register with QObject* callback
MySingleton::typeId = qmlRegisterSingletonType&lt;MySingleton&gt;(...);

// Retrieve as QObject*
QQmlEngine engine;
MySingleton* instance = engine.singletonInstance&lt;MySingleton*&gt;(MySingleton::typeId);

QJSValue example:

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

// Retrieve as QJSValue
QQmlEngine engine;
QJSValue instance = engine.singletonInstance&lt;QJSValue&gt;(typeId);

It is recommended to store the QML type id during registration, e.g. as a static member in the singleton class. Otherwise, a costly lookup via qmlTypeId() has to be performed at run-time.

This function was introduced in Qt 5.12.

See Also

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 th