为 QML 创建 C++ 插件

创建插件

QML engine 可加载 QML 的 C++ 插件。此类插件通常在 QML 扩展模块中提供,可为导入模块的 QML 文档中的客户端提供类型。一个模块至少需要一个已注册的类型才算有效。

QQmlEngineExtensionPlugin 是一个插件接口,让你创建可动态加载到 QML 应用程序中的 QML 扩展。这些扩展允许 QML 引擎使用自定义 QML 类型。

要编写 QML 扩展插件:

  1. 子类QQmlEngineExtensionPlugin 并使用Q_PLUGIN_METADATA() 宏向 Qt XML 元对象系统注册插件。
  2. 使用QML_ELEMENTQML_NAMED_ELEMENT() 宏声明 QML 类型。
  3. 配置编译文件。

    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>
  4. 如果使用 qmake,请创建一个qmldir 文件来描述插件。注意 CMake 默认会自动生成qmldir 文件

QML 扩展插件适用于特定应用程序或类似库的插件。库类插件应仅限于注册类型,因为对引擎根上下文的任何操作都可能在库用户的代码中引起冲突或其他问题。

注意: 使用 CMakeqt_add_qml_moduleAPI 时,会自动生成一个插件。它将负责类型注册。只有在有特殊要求的情况下,如注册自定义图像提供者,才需要编写自定义插件。在这种情况下,请向qt_add_qml_module 调用NO_GENERATE_PLUGIN_SOURCE,禁止生成默认插件。

作为优化,链接器可能会错误地删除生成的类型注册函数。您可以在代码中声明一个指向该函数的合成易失性指针来防止这种情况。如果模块名为 "my.module",则应在全局作用域中添加前向声明:

void qml_register_types_my_module();

然后在任何与注册属于同一二进制的函数的实现中添加以下代码片段:

volatile auto registration = &qml_register_types_my_module;
Q_UNUSED(registration);

参考

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.