Qt Protobuf 可变的获取器
生成的 Qt Protobuf 消息允许通过可变获取器访问消息类型的字段。这些获取器以mut 为前缀,并返回指向该字段的非const引用。
message Point {
double x = 1;
double y = 2;
}
message Line {
Point start = 1;
Point end = 2;
}上述.proto 方案为Line 消息生成了以下代码:
class Line : public QProtobufMessage
{
const Point &start() const &;
Point &mutStart() &;
...
const Point &end() const &;
Point &mutEnd() &;
...
}对于start 和end 字段,qtprotobufgen生成器会创建额外的可变获取器:mutStart 和mutEnd 。使用这些获取器可直接修改字段,无需创建中间消息:
Line line;
// 将线的起点设置为 (5.0, 5.0)
line.mutStart().setX(5.0);
line.mutStart().setY(5.0);
// 将线的起点设置为 (10.0, 20.0)
line.mutEnd().setX(10.0);
line.mutEnd().setY(20.0);
// 显示 Line 数据
qDebug().nospace() << "start: (" << line.start().x() << "," << line.start().y() << ") "
"end: (" <<line.end().x()<< "," <<line.end().y()<< ")";调用可变的获取器会执行任何必要的字段分配,并允许您直接修改底层数据。
警告:可变 获取器会在字段名前添加前缀“mut ”。如果一条消息中包含名为field 和mutField 的字段,则会发生命名冲突。当前不支持这种情况,并将导致生成器错误。
© 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.