本页内容

Qt Protobuf Well-Known Types C++ Classes

Qt Protobuf 的“已知类型”模块为“已知类型”包中提供的某些类型提供了支持。更多内容...

该模块于 Qt 6.6 版本中引入。

类

QtProtobuf::Any

一个用于简化 protobuf Any 类型操作的辅助类

详细描述

QtProtobufWellKnownTypes 包含以下Protobuf 已知类型:支持的类型:

使用 ProtobufWellKnownTypes 库

要在项目中使用已知类型,您可以在接口中包含相应的 Google .proto 文件:

syntax = "proto3";
package somepackage;
import "google/protobuf/any.proto";
message Message {
    google.protobuf.Any payload = 1;
}

要使用所列类型,您必须通过在CMakeLists.txt文件中添加以下行来链接ProtobufWellKnownTypes 库:

target_link_libraries(YourTargetName PRIVATE Qt::ProtobufWellKnownTypes)

为 ProtobufWellKnownTypes 添加 QML 支持

ProtobufWellKnownTypes 库目前不提供 QML 支持。虽然该支持将在未来版本中实现,但目前您可以按照以下说明,将Qt Protobuf 的已知类型扩展为与 QML 兼容的类型。例如,Empty常被用作 RPC 方法的输入或输出。请参见下文:

syntax = "proto3";
package qtgrpc.examples;
import "google/protobuf/empty.proto";
service ExampleService {
    rpc emptyMethod(google.protobuf.Empty) returns (google.protobuf.Empty) {}
}

要在 QML 中调用emptyMethod ,请通过在项目的头文件(.h )中添加以下代码来声明 `google.protobuf.Empty ` 类型:

#include "google/protobuf/empty.qpb.h"

struct GoogleProtobufAPI
{
    Q_GADGET
    QML_FOREIGN(google::protobuf::Empty)
    QML_STRUCTURED_VALUE
    QML_VALUE_TYPE(protobufEmpty)
};

之后,您就可以在 QML 中使用 `protobufEmpty ` 值类型了。请参见以下示例:

import qtgrpc.examples
import QtQuick
import QtGrpc

Item {
    id: root
    property protobufEmpty value: null

    ServiceClient {
        id: grpcClient
        channel: grpcChannel.channel
    }

    Item {
        Component.onCompleted: {
            grpcClient.emptyMethod(value, messageCallback, errorCallback, grpcCallOptions);
        }
    }
}

QML_STRUCTURED_VALUE 宏还支持以下语法:

Component.onCompleted: {
    grpcClient.emptyMethod({}, messageCallback, errorCallback, grpcCallOptions);
}

另请参阅 QML_VALUE_TYPE 和QML_STRUCTURED_VALUE 。

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