qt_generate_foreign_qml_types
将一个目标中的类型注册到 QML 模块中。
该命令定义在Qt6 包的Qml 组件中,可按以下方式加载:
find_package(Qt6 REQUIRED COMPONENTS Qml)用法
qt_generate_foreign_qml_types(
source_target
destination_qml_target
)如果禁用了无版本命令,请改用qt6_generate_foreign_qml_types() 。它支持与本命令相同的参数集。
描述
qt_generate_foreign_qml_types 从 `source_target ` 中提取通过 QML 注册宏(如 `QML_ELEMENT`)标记的类型,并将它们作为外部类型注册到 QML 模块 `destination_qml_target` 中。
当需要创建一个支持可选 QML 集成的库,且不直接依赖 QML 时,此操作会非常有用。
// myclass.h
#include <QtQmlIntegration/qqmlintegration.h>
class MyClass : public QObject
{
QML_ELEMENT
Q_OBJECT
// [...]
};# CMakeLists.txt
qt_add_library(mylib myclass.h ...)
target_link_libraries(mylib PRIVATE Qt::Core Qt::QmlIntegration)
qt_add_qml_module(mylib_declarative
VERSION 1.0
URI "mylib"
...
)
qt_generate_foreign_qml_types(mylib mylib_declarative)注意:在上例中, mylib 不依赖于QtQml 或QtQuick ,而仅依赖于仅包含头文件的QmlIntegration 目标(用于qqmlintegration.h 头文件,该头文件提供了QML_ELEMENT 宏)。
其效果等同于在 QML 库中使用QML_FOREIGN 并配合自定义结构体来暴露类型。
注意:为了 实现自定义行为(例如将具有自身生命周期的现有单例实例暴露给 QML),您应将自定义类型添加到您的 QML 库中(如上例中的 mylib_declarative)。 相应地,您应从原始 C++ 类中省略 `QML_ELEMENT ` 及类似宏,以确保 `qt_generate_foreign_qml_types()` 不会为其生成更多的 QML 集成结构体。QML 宏以及任何单例工厂函数均可添加到包含 `QML_FOREIGN` 的结构体中。
© 2026 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.