The QML engine loads C++ plugins for QML. Such plugins are usually provided in a QML extension module, and can provide types for use by clients in QML documents that import the module. A module requires at least one registered type to be considered valid.
QQmlEngineExtensionPlugin is a plugin interface that lets you create QML extensions that can be loaded dynamically into QML applications. These extensions allow custom QML types to be made available to the QML engine.
To write a QML extension plugin:
Configure your build file.
CMake:
qt_add_qml_module(<target> URI <my.import.name> VERSION 1.0 QML_FILES <app.qml> NO_RESOURCE_TARGET_PATH )
qmake:
CONFIG += qmltypes QML_IMPORT_NAME = <my.import.name> QML_IMPORT_MAJOR_VERSION = <version>
QML extension plugins are for either application-specific or library-like plugins. Library plugins should limit themselves to registering types, as any manipulation of the engine's root context may cause conflicts or other issues in the library user's code.
注意:
When using the CMake
qt_add_qml_module
API, a plugin will be generated automatically for you. It will take care of type registration. You only need to write a custom plugin if you have special requirements, such as registering custom image providers. In that case, pass
NO_GENERATE_PLUGIN_SOURCE
到
qt_add_qml_module
call to disable the generation of the default plugin.
The linker might erroneously remove the generated type registration function as an optimization. You can prevent that by declaring a synthetic volatile pointer to the function somewhere in your code. If your module is called "my.module", you would add the forward declaration in global scope:
void qml_register_types_my_module();
Then add the following snippet of code in the implementation of any function that's part of the same binary as the registration:
volatile auto registration = &qml_register_types_my_module; Q_UNUSED(registration);