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 从 提取通过 QML 注册宏(如 )标记的类型,并将它们注册为 QML 模块 中的外来类型。source_target QML_ELEMENT 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 并不依赖于QtQmlQtQuick ,而只依赖于仅头文件的 QmlIntegration 目标(qqmlintegration.h头文件,它提供了QML_ELEMENT 宏)。

其效果等同于在 QML 库中使用QML_FOREIGN 和自定义结构来公开类型。

注意: 为了实现自定义行为,例如向 QML 公开一个有自己生命周期的现有单例,你应该在 QML 库中添加自定义类型(上例中的 mylib_declarative)。反过来,你应该省略原始 C++ 类中的QML_ELEMENT 和类似宏,这样 qt_generate_foreign_qml_types() 就不会为它们生成更多的 QML 整合结构体。QML 宏以及任何单例工厂函数,都可以添加到包含QML_FOREIGN 的结构体中。

© 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.