C++ 与 QML 代码之间的接口Qt Positioning

概述

Qt Positioning 使用两种方法简化 C++ 和 QML 代码之间的位置数据交换。

QtPositioning 中的直接 C++ 值集成

从 Qt 5.5 开始,将非基于QObject 的数据类型集成到 Qt Qml 中变得更加容易。这是通过向QtQml 添加Q_GADGET 支持实现的。该宏将类转换为QObject 的轻量级版本,而无需QObject 继承。同时,它保留了QMetaObject 的反射功能。因此,它们可以直接暴露在 QML 中。

大量与 Position 相关的数据类型被转换为Q_GADGETs。它们保留了 API 和值类型特征,但可通过QMetaObject 进行内省。

QML_ANONYMOUS 宏用于将这些类型暴露给 QML 环境。更多详情和可用宏的完整列表,请参阅QQmlEngine 文档。

然而,这些类不能直接用这个宏扩展,因为我们不想让Qt Positioning 依赖QtQml 。因此,我们为每个类创建了一个辅助类,并使用QML_FOREIGN 宏:

struct QGeoCoordinateForeign
{
    Q_GADGET
    QML_FOREIGN(QGeoCoordinate)
    QML_ANONYMOUS
    QML_ADDED_IN_VERSION(5, 0)
};

上述定位类型的注册由QtPositioning QML 插件自动完成一次。

基于 QVariant 的集成

本节介绍如何集成QGeoAddressQGeoLocation

地址 - QGeoAddress

Address.address 属性用于在 C++ 和 QML 代码之间提供接口。首先必须从 C++ 获取Address 对象的指针,然后使用property() 和setProperty() 函数获取和设置address 属性。

以下代码从 C++ 获取QGeoAddress 对象:

 QGeoAddress geoAddress = qmlObject->property("address").value<QGeoAddress>();

以下代码根据 C++ 中的QGeoAddress 对象设置 QML 对象的地址属性:

qmlObject->setProperty("address", QVariant::fromValue(geoAddress));

位置 - QGeoLocation

Location.location 属性用于提供 C++ 和 QML 代码之间的接口。首先必须从 C++ 获取Location 对象的指针,然后使用property() 和setProperty() 函数获取和设置location 属性。

下面的代码从 C++ 获取QGeoLocation 对象:

QGeoLocation geoLocation = qmlObject->property("location").value<QGeoLocation>();

以下代码根据 C++ 中的QGeoLocation 对象设置 QML 对象的 location 属性:

qmlObject->setProperty("location", QVariant::fromValue(geoLocation));

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