Qt GRPC
Qt GRPC,结合 Qt Protobuf 模块配合使用,可实现与 gRPC™ 服务器进行快速且节省空间的通信。它将gRPC 服务无缝集成到Qt框架中,无论服务器是否基于Qt,都能实现跨不同编程语言或环境的通信。
概述
gRPC 是一个跨平台、高性能的远程过程调用(RPC)框架。它使用 Protobuf 编译器(protoc )从 protobuf 模式中的 `service ` 部分生成适用于各种编程语言的客户端和服务器接口。 它通常用于连接微服务架构中的服务,或将移动应用和浏览器与后端系统相连。更多详情请参阅gRPC 入门指南。
Qt GRPC 由 C++ 和Qt Quick API 组成,这些 API 利用广为人知的信号与插槽(Signals & Slots)机制来处理远程过程调用(RPC)的异步特性。它还提供了命令行工具和 CMake API,以简化使用protoc 生成 Qt 专用接口的过程。
Qt GRPC 目前支持客户端功能。这意味着它可以与兼容 gRPC 的服务器进行通信。该服务器可以是您自己的、带有 protobuf API 的服务器,也可以是公开可用的 API,例如Google API。
使用该模块
模块先决条件
protoc,即 Protocol Buffers 编译器,是运行 Qt 代码生成器插件的必要条件。请参阅Protoc 安装指南。- 可选:SSL支持。
- 可选:运行示例所需的gRPC C++。
注意: 有关如何安装gRPC 和Protobuf,以及运行Qt GRPC 示例的说明,请参阅 《使用vcpkg在Windows上进行安装的示例》。
C++ API
若要将 protobuf 文件添加到基于 Qt 的项目中并生成所需的源代码,请使用protoc 编译器,并配合qtgrpcgen 和qtprotobufgen 这两个 Qt 插件。
- qtprotobufgen 工具可从 protobuf消息定义生成 Qt 类。请使用qt_add_protobufCMake 命令来自动化此过程。
- qtgrpcgen 工具可从 protobuf服务定义生成接口。使用qt_add_grpcCMake 命令可实现此过程的自动化。
一个使用 `Qt GRPC ` 的 CMake 项目文件的简易示例如下:
cmake_minimum_required(VERSION 3.16...3.22)
project(MyProject)
find_package(Qt6 REQUIRED COMPONENTS Protobuf Grpc)
qt_standard_project_setup()
qt_add_executable(MyApp main.cpp)
qt_add_protobuf(MyApp
PROTO_FILES
path/to/messages.proto
)
qt_add_grpc(MyApp CLIENT
PROTO_FILES
path/to/service.proto
)
target_link_libraries(MyApp PRIVATE Qt6::Protobuf Qt6::Grpc)QML API
该模块的 QML 类型可通过 `QtGrpc ` 导入获取。要使用这些类型,请在您的 .qml 文件中添加以下导入语句:
import QtGrpc文章与指南
参考文献
示例
许可与署名
Qt GRPC 模块由The Qt Company 提供商业许可。此外,该模块还遵循自由软件许可协议:GNU 通用公共许可证第 3 版。更多详情请参阅Qt 许可条款。
此外,Qt 6.12.0 中的Qt GRPC 可能包含遵循以下宽松许可协议的第三方模块:
Apache 2.0 许可协议 |
© 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.