在本页

Qt Protobuf Well-Known Types C++ Classes

Qt Protobuf Well-Known Types 模块为Well-Known Types包中的部分类型提供支持。更多

该模块在 Qt 6.6 中引入。

QtProtobuf::Any

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

详细描述

QtProtobufWellKnownTypes 包含以下Protobuf Well-Known 类型:支持的类型:

使用 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_TYPEQML_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.