QGroundControl VehicleConfig 页面生成机制深度解析:从 JSON 定义到 Setup 配置页
QGroundControl VehicleConfig 页面生成机制深度解析:从 JSON 定义到 Setup 配置页
QGroundControl 的 Vehicle Setup(电源 Power、安全 Safety 等)页面并非手写 QML,而是由一套「JSON 页面定义 + Python 生成器」的代码生成流水线在构建期自动产出。本文以 docs/tr/qgc-dev-guide/views/vehicle_config_generation.md 为骨架,结合仓库内真实源码、页面定义与测试用例,完整讲解这套机制的架构、JSON Schema、构建接线方式,并给出新增一个生成式 Setup 页面的可操作步骤。读完本文,你将掌握如何在 QGroundControl 中通过纯 JSON 声明快速扩展飞控配置页面,并理解生成的 QML 与 C++ 组件之间的协作原理。
生成流水线总览
官方文档给出的核心流水线共四步,每一步在仓库中都有对应的实体:
- JSON 页面定义:位于
src/AutoPilotPlugins/{APM,PX4}/VehicleConfig/*.VehicleConfig.json,例如 PX4/VehicleConfig/Power.VehicleConfig.json、PX4/VehicleConfig/Safety.VehicleConfig.json、APM/VehicleConfig/APMPower.VehicleConfig.json; - Python 生成器:核心逻辑位于 tools/generators/config_qml/page_generator.py(入口为 tools/generators/config_qml/generate_pages.py,渲染逻辑在 tools/generators/config_qml/emit.py 与 tools/generators/config_qml/control_renderers.py);
- 生成的 QML:输出到构建目录
build/src/AutoPilotPlugins/{APM,PX4}/generated/,文件命名规则为<Name>.VehicleConfig.json → <Name>Component.qml(见 generate_pages.py 中的_output_name函数); - C++ 组件类:例如
APMPowerComponent,通过setupSource()返回生成的 QML 的qrc:URL 并加载到 Setup 面板。
从源码结构看,整个设计的目标是:新增配置页面时,绝大多数工作收敛为"写一个 JSON 文件 + 一个极简 C++ 子类",QML 界面细节由生成器统一保证风格一致。
生成器的构建期接线
代码生成在构建阶段由 CMake 驱动。每个飞控插件(firmware plugin)的 CMakeLists.txt 都声明了一个独立的目标:
- src/AutoPilotPlugins/APM/CMakeLists.txt —— 目标
GenerateConfigQmlAPM; - src/AutoPilotPlugins/PX4/CMakeLists.txt —— 目标
GenerateConfigQmlPX4。
两个目标实际执行的都是:
python -m tools.generators.config_qml.generate_pages \
--pages-dir <pages_dir> \
--output-dir <build_gen_dir>
其中 generate_pages.py 支持三个命令行参数(见 generate_pages.py):
| 参数 | 必填 | 说明 |
|---|---|---|
--pages-dir |
是 | 存放 *.VehicleConfig.json 的目录 |
--output-dir / -o |
是 | 生成的 QML 输出目录 |
--dry-run / -n |
否 | 只打印到标准输出,不写文件,便于调试 |
生成器脚本内部会按字典序扫描 --pages-dir 下所有 *.VehicleConfig.json,逐个解析并渲染出 QML 文件(无匹配文件时仅打印警告,不会报错)。
qgc_add_qml_codegen 封装
两个 CMake 目标都通过 cmake/modules/QGCQmlCodegen.cmake 提供的 qgc_add_qml_codegen() 函数创建。该函数的关键行为:
GENERATE_AT_CONFIGURE:在 CMake configure 阶段就执行生成器,并把生成器源文件与 JSON 输入通过CMAKE_CONFIGURE_DEPENDS注册为配置依赖——任何生成器.py、模板.j2或*.VehicleConfig.json的改动都会自动触发重新配置与重新生成;QML_NAMES:声明期望产出的 QML 文件名列表,生成完毕后会逐一校验文件确实存在,缺失即报FATAL_ERROR;OUTPUT_DIR:强制必须是绝对路径,且必须位于CMAKE_BINARY_DIR之下(QGCQmlCodegen.cmake);- 通过
add_custom_command挂到构建依赖,确保qt_add_qml_module打包生成文件之前先生成完毕。
以 PX4 为例,CMakeLists.txt 中生成的 PowerComponent.qml、SafetyComponent.qml 被直接列入 qt_add_qml_module(AutoPilotPluginsPX4Module URI QGroundControl.AutoPilotPlugins.PX4 ...) 的 QML_FILES,编译进 QGroundControl.AutoPilotPlugins.PX4 QML 模块,同时两个 JSON 源文件也被加入 RESOURCES 以便运行时读取。
VehicleComponent:生成页面的 C++ 侧基类
VehicleComponent(src/AutoPilotPlugins/VehicleComponent.h 与 src/AutoPilotPlugins/VehicleComponent.cc)是生成页面的 C++ 侧公共基类。它在运行时再次解析同一个 JSON 文件,为侧边栏和页面提供三类能力:
- 构建侧边栏 section 列表:
sectionIds()会调用_ensureSectionsCached()惰性解析vehicleConfigJson()指向的 JSON,遍历每个 section 的title,并把带repeat的 section 按探测到的实例数量展开成多个 section ID(例如Power.VehicleConfig.json的Batterysection 展开为Battery 1、Battery 2…); - 动态过滤被禁用的重复实例:当 section 配置了
enableParam/disabledParamValue时,sectionIds()会检查对应参数的rawValue,若等于禁用值则从列表中移除该 section,并追加disabledSection.heading对应的「禁用」条目(VehicleComponent.cc); - 连接信号保持侧边栏实时更新:
setupTriggerSignals()对每个 repeat 组的 enableParam 建立Fact::valueChanged → sectionIdsChanged连接,用户切换开关时侧边栏立即重算(VehicleComponent.cc)。
子类因此只需实现两个方法:vehicleConfigJson() 返回 JSON 的资源路径,setupSource() 返回生成的 QML 的 qrc: URL。以 PX4 的 PowerComponent.cc 为例:
QUrl PowerComponent::setupSource(void) const
{
// Generated from Power.VehicleConfig.json
return QUrl::fromUserInput("qrc:/qml/QGroundControl/AutoPilotPlugins/PX4/PowerComponent.qml");
}
QString PowerComponent::vehicleConfigJson(void) const
{
return QStringLiteral(":/qml/QGroundControl/AutoPilotPlugins/PX4/VehicleConfig/Power.VehicleConfig.json");
}
从源码结构还可以看出,sectionIds() 对 repeat 展开支持两种模式(VehicleComponent.cc):
- 默认模式:从
startIndex起,用paramPrefix + idx + probePostfix探测参数是否存在(如 PX4 的BAT1_SOURCE、BAT2_SOURCE…),不存在即停止; apm_battery模式:针对 ArduPilot 电池的特殊编号规则(BATT_、BATT1_…BATT8_、BATTA_…),探测_MONITOR参数,最多 16 个实例。
组件类由各飞控插件的 AutoPilotPlugin 子类创建并注册,例如 PX4AutoPilotPlugin.cc 中 new PowerComponent(...)、new SafetyComponent(...),以及 APMAutoPilotPlugin.cc 中 new APMPowerComponent(...)、new APMLoggingComponent(...) 等。
JSON 页面定义 Schema 详解
完整的 Schema 参考位于 tools/generators/config_qml/README.md,本文基于该文档并结合 model.py 的校验逻辑展开。
顶层对象
| Key | 类型 | 必填 | 说明 |
|---|---|---|---|
fileType |
"VehicleConfig" |
是 | 必须为 "VehicleConfig" |
version |
1 |
是 | Schema 版本,当前为 1 |
constants |
object | 否 | 可在 QML 表达式中复用的命名字面量 |
params |
object | 否 | 命名参数 Fact 声明(详见下文) |
bindings |
object | 否 | 页面的命名 QML 属性绑定表达式 |
imports |
array of strings | 否 | 额外需要输出的 QML import 行 |
controllerType |
string | 否 | 页面控制器的 QML 类型,默认 FactPanelController |
sections |
array of Section | 是 | 页面 Section,自上而下渲染 |
model.py 中 _ALLOWED_ROOT_KEYS(model.py)会拒绝任何未列出的顶层键,拼写错误会直接报错——这是 JSON Schema 的"硬校验"实现,测试用例 tools/tests/test_config_qml_generator.py 中 TestUnknownKeyRejection 专门覆盖了根键、section 键、control 键、repeat 键的拼写错误场景。
params:参数 Fact 声明
每个 key 会成为页面根 Item 上的一个 QML 属性,value 可以是参数名字符串或对象:
"params": {
"rateParam": "LOG_FILE_RATEMAX",
"backendParam": {
"name": "LOG_BACKEND_TYPE",
"required": false,
"existsOnly": false
}
}
| Key | 类型 | 默认值 | 说明 |
|---|---|---|---|
name |
string | — | MAVLink 参数名 |
required |
bool | false |
true → 生成 getParameterFact(-1, name)(参数缺失时断言报错);false → getParameterFact(-1, name, false)(缺失时返回 null) |
existsOnly |
bool | false |
true → 生成 parameterExists(-1, name),暴露布尔值而非 Fact |
简写 "rateParam": "LOG_FILE_RATEMAX" 等价于 { "name": "LOG_FILE_RATEMAX", "required": false }。三种形式对应的 QML 生成逻辑见 emit.py 的 _param_line 函数。
section
| Key | 类型 | 必填 | 说明 |
|---|---|---|---|
title |
string | 是 | Section 标题(可翻译,同时作为 section ID 参与过滤) |
image |
string | 否 | Section 图标的 qrc: 路径 |
showWhen |
string | 否 | QML 表达式,为假时隐藏该 Section |
keywords |
array of strings | 否 | 供 Section 过滤器使用的额外搜索词 |
controls |
array of Control | 是* | 要渲染的控件 |
component |
string | 否 | 逃生通道——直接嵌入手写 QML 组件名而非生成控件 |
repeat |
Repeat | 否 | 对每个带索引的参数实例重复渲染该 Section |
* 当设置 component 时 controls 可不填。注意校验器会拒绝 title 中出现 {index} 占位符(model.py),因为 C++ 侧 sectionIds() 无法展开占位符,会导致生成的 section ID 与 QML 永远匹配不上。
control
| Key | 类型 | 必填 | 说明 |
|---|---|---|---|
param |
string | param/setting/component/actionButton 四选一 |
MAVLink 参数名 |
setting |
string | — | 设置项 Fact 路径,如 "flyViewSettings.showObstacleDistanceOverlay" |
label |
string | 否 | 覆盖标签;为空时使用 fact.shortDescription |
control |
string | 否 | 显式控件类型(见下表);缺省时按 Fact 元数据自动探测 |
optional |
bool | false |
参数可能不存在,使用 getParameterFact(-1, name, false);参数缺失时控件隐藏(visible: fact !== null) |
showWhen |
string | 否 | 附加可见性 QML 表达式;与 optional: true 组合时,控件仅在参数存在且表达式为真时可见 |
enableWhen |
string | 否 | 绑定到 enabled 的 QML 表达式 |
indent |
bool | false |
通过 Layout.leftMargin 缩进控件 |
warning |
bool | false |
仅对 label 生效,用警告色渲染文本 |
smallFont |
bool | false |
仅对 label 生效,使用更小字号 |
component |
string | 否 | 内联逃生通道——手写 QML 组件名 |
optional 与 showWhen 的组合可见性由 _vis_expr()(model.py)生成,会合成 fact !== null && (showWhen) 形式的表达式。
控件类型表
control 键决定生成的控件。缺省时生成器根据 Fact 元数据自动探测(布尔 → 复选框、枚举 → 下拉框等),对应关系见 control_renderers.py 的 _RENDERERS 分发表:
control 值 |
生成的控件 | 附加键 |
|---|---|---|
| (缺省) | 自动探测 | — |
combobox |
LabelledFactComboBox |
enumValues 手动值/标签列表 |
textfield |
LabelledFactTextField |
description 字段下方的可选帮助文本 |
checkbox |
FactCheckBoxSlider |
— |
toggleCheckbox |
带自定义逻辑的 QGCCheckBoxSlider |
toggleCheckbox |
slider |
带可选启用复选框和邻接按钮的 Slider | sliderMin、sliderMax、enableCheckbox、button |
factslider |
SettingsGroupLayout 内的 FactSlider |
sliderFrom、sliderTo、majorTickStepSize、decimalPlaces、description、linkedParams |
radiogroup |
标签 + 单选按钮 | options、raw |
bitmask |
FactBitmask |
firstEntryIsAll |
bitmaskCheckbox |
FactBitMaskCheckBoxSlider |
bitMask |
dialogButton |
打开弹出对话框的按钮 | dialogButton |
actionButton |
调用控制器方法的独立按钮 | actionButton |
label |
静态文本标签 | warning、smallFont |
combobox + enumValues
当参数没有枚举元数据(例如固件未暴露)时,可手动提供值/标签列表。value 必须是数字或字符串(布尔会被 _parse_enum_value_entry 显式拒绝,见 model.py),label 必须是字符串:
{
"param": "EK3_LOG_LEVEL",
"control": "combobox",
"optional": true,
"enumValues": [
{ "value": 0, "label": "Full logging" },
{ "value": 1, "label": "XKF4 scaled innovations only" },
{ "value": 2, "label": "XKF4 and GSF" },
{ "value": 3, "label": "Disabled" }
]
}
textfield 附加键
| Key | 类型 | 说明 |
|---|---|---|
description |
string | 字段下方以小字号渲染的帮助文本,会将该控件包裹进 ColumnLayout |
factslider 附加键
| Key | 类型 | 说明 |
|---|---|---|
sliderFrom |
number | 最小值覆盖 |
sliderTo |
number | 最大值覆盖 |
majorTickStepSize |
number | 刻度间隔 |
decimalPlaces |
number | 小数精度 |
description |
string | 滑块上方的帮助文本 |
linkedParams |
object | { "PARAM_NAME": "expression" },onValueChanged 时联动更新 |
linkedParams 表达式中 value 指滑块当前值,例如:
"linkedParams": {
"ATC_RAT_PIT_P": "value",
"ATC_RAT_PIT_I": "value * 2"
}
slider 附加键
| Key | 类型 | 说明 |
|---|---|---|
sliderMin |
number | 最小值覆盖 |
sliderMax |
number | 最大值覆盖 |
enableCheckbox |
object | { "checked": "expr", "onClicked": "body" } |
button |
object | { "text": "label", "onClicked": "body", "enabled": "expr" } |
radiogroup 附加键
| Key | 类型 | 说明 |
|---|---|---|
options |
array | [ { "text": "Label", "value": 0 } ] |
raw |
bool | 比较时用 rawValue 而非 value |
bitmask / bitmaskCheckbox 附加键
| Key | 类型 | 说明 |
|---|---|---|
firstEntryIsAll |
bool | 第一个复选框作为"全选/全不选"开关 |
bitMask |
number | 该复选框控制的特定位掩码值 |
repeat:重复 Section
用于对每个带索引的参数实例(如 BAT1_…、BAT2_…)重复渲染一个 Section:
| Key | 类型 | 说明 |
|---|---|---|
paramPrefix |
string | 参数前缀,如 "BAT" |
probePostfix |
string | 用于探测实例数量的后缀,如 "_SOURCE" |
startIndex |
number | 起始索引(默认 1) |
firstIndexOmitsNumber |
bool | 为 true 时索引 1 表示为 "BAT" 而非 "BAT1" |
indexing |
string | 自定义索引模式(如 "apm_battery") |
enableParam |
string | 必须与 disabledParamValue 不同,Section 才显示的参数 |
disabledParamValue |
string | "禁用"值的绑定名 |
disabledSection |
object | 禁用实例时显示的同级 Section |
disabledSection 支持两个键:heading(禁用 Section 的标题)和 enabledParamValue(启用时写入的值;为空则使用下拉框)。校验器强制 enableParam 与 disabledParamValue 必须成对出现,只写其一会在加载时直接抛错(model.py)。
真实页面剖析:三份有代表性的定义
PX4 Power:repeat + dialogButton 的典型用法
Power.VehicleConfig.json 展示了两个重点特性:
带 repeat 的 Battery Section:paramPrefix: "BAT"、probePostfix: "_SOURCE",实例数由探测 BAT1_SOURCE、BAT2_SOURCE… 是否存在决定。控件中的 param 使用后缀(_SOURCE、_N_CELLS、_CAPACITY),完整参数名在运行期由 _fullParamName("_SOURCE") 拼出;showWhen 中也统一用 _fullParamName,例如:
{
"param": "_CAPACITY",
"label": "Battery capacity (mAh)",
"optional": true,
"showWhen": "controller.parameterExists(-1, _fullParamName(\"_CAPACITY\"))",
"description": "Set to -1 to disable. When set to a positive value, enables coulomb counting for more accurate state-of-charge and time-remaining estimates."
}
dialogButton 控件:_V_DIV(电压分压比)与 _A_PER_V(安培/伏特)都挂了一个"Calculate"按钮,点击后打开 CalcVoltageDividerDialog / CalcAmpsPerVoltDialog 对话框,并通过 dialogParams把batteryIndex: "_rawIndex"` 传入对话框:
{
"param": "_V_DIV",
"label": "Voltage divider",
"optional": true,
"showWhen": "controller.parameterExists(-1, _fullParamName(\"_V_DIV\"))",
"control": "dialogButton",
"dialogButton": {
"text": "Calculate",
"dialogComponent": "CalcVoltageDividerDialog",
"buttonAfter": false,
"dialogParams": {
"batteryIndex": "_rawIndex"
}
}
}
此外该页面还演示了纯 label 的用法——ESC 校准前的两条警告文本(warning: true 使第一条渲染为警告色)。
PX4 Safety:constants/params/bindings + radiogroup + enableWhen 的组合
Safety.VehicleConfig.json 是顶层键最齐全的示例:
- constants 定义三个 RTL 落地延迟的语义常量(
0立即落地、-1无限期盘旋、60默认盘旋秒数),后续 radiogroup 的checked表达式直接引用常量名; - params 声明六个具名 Fact,其中
_cpDist、_fenceRadius、_fenceAlt、_disarmLandDelay、_rtlLandDelay为required: true,_landSpeedMCExists为existsOnly: true(暴露布尔值); - slider + enableCheckbox:碰撞防护距离、围栏半径/高度三个滑块都带启用复选框,例如
onClicked: "{ _cpDist.rawValue = enableCheckBoxChecked ? 5 : -1 }"; - radiogroup + 常量引用:RTL 落地策略用
value引用常量、checked引用_rtlLandDelay的取值区间:
{
"param": "RTL_LAND_DELAY",
"label": "Return to launch, then:",
"control": "radiogroup",
"options": [
{
"label": "Land immediately",
"value": "_rtlLandDelayParamValueLandImmediately",
"checked": "_rtlLandDelay.value === _rtlLandDelayParamValueLandImmediately"
},
{
"label": "Loiter and do not land",
"value": "_rtlLandDelayParamValueLoiterIndefinitely",
"checked": "_rtlLandDelay.value < _rtlLandDelayParamValueLandImmediately"
},
{
"label": "Loiter and land after specified time",
"value": "_rtlLandDelayParamValueLoiterDefault",
"checked": "_rtlLandDelay.value > _rtlLandDelayParamValueLandImmediately"
}
]
}
- enableWhen 联动:
Loiter time(RTL_LAND_DELAY再次出现,作为数值输入)仅在_rtlLandDelay.value > 0时可用;Loiter altitude(RTL_DESCEND_ALT)在非"立即落地"时可用; - setting 控件:Object Detection 小节里的
"setting": "flyViewSettings.showObstacleDistanceOverlay"演示了直接绑定 QGroundControl 设置项而非飞控参数。
APM Power:apm_battery 索引 + 禁用过滤的完整形态
APMPower.VehicleConfig.json 是 repeat 机制最复杂的用例:
"repeat": {
"paramPrefix": "BATT",
"probePostfix": "MONITOR",
"indexing": "apm_battery",
"enableParam": "MONITOR",
"disabledParamValue": "_monitorParamValueDisabled",
"disabledSection": {
"heading": "Disabled Batteries",
"enabledParamValue": "_monitorParamValueAnalogVoltageAndCurrent"
}
}
indexing: "apm_battery"让生成器与 C++ 侧都采用 ArduPilot 电池命名规则:BATT_、BATT1_…BATT8_、BATTA_…(对应 JS 函数_battPrefixForIndex与 C++ 的battPrefixlambda,见 repeat_count_apm_battery.qml.j2 与 VehicleComponent.cc);enableParam: "MONITOR"+disabledParamValue: "_monitorParamValueDisabled":当某电池的BATTn_MONITOR等于常量_monitorParamValueDisabled(0)时,该实例从侧边栏移除,统一收进 "Disabled Batteries" 分组;enabledParamValue指定重新启用时写入的值(_monitorParamValueAnalogVoltageAndCurrent= 4);showWhen中演示了复杂表达式——VOLT_MULT仅在监视器为电压相关模式(3/4/25)时出现:
"showWhen": "controller.parameterExists(-1, _fullParamName(\"VOLT_MULT\")) && [_monitorParamValueAnalogVoltageOnly, _monitorParamValueAnalogVoltageAndCurrent, _monitorParamValueAnalogVoltageSyntheticCurrent].includes(controller.getParameterFact(-1, _fullParamName(\"MONITOR\")).rawValue)"
APM Logging:bitmask 与 enumValues 的直接使用
APMLogging.VehicleConfig.json 全部由 optional: true 的简单控件构成:LOG_BACKEND_TYPE、LOG_BITMASK 用 bitmask 控件,日志速率用默认 textfield,EK3_LOG_LEVEL 用带 enumValues 的 combobox,是最适合作为"第一个上手副本"的页面。
新增一个生成式 Setup 页面:完整步骤
步骤 1:创建 JSON 页面定义
在对应飞控插件的 VehicleConfig/ 目录下新建 JSON 文件,例如:
src/AutoPilotPlugins/APM/VehicleConfig/MyFeature.VehicleConfig.json
参考 tools/generators/config_qml/README.md 中的完整 Schema。最小可用骨架:
{
"fileType": "VehicleConfig",
"version": 1,
"sections": [
{
"title": "Storage",
"keywords": ["logging", "log", "sd card"],
"controls": [
{
"param": "LOG_BACKEND_TYPE",
"label": "Logging backends",
"optional": true,
"control": "bitmask"
},
{
"param": "LOG_MAX_FILES",
"label": "Maximum retained log files",
"optional": true
}
]
}
]
}
步骤 2:创建继承 VehicleComponent 的 C++ 子类
以 PX4 的 SafetyComponent.cc 或 APM 的 APMPowerComponent.cc 为模板,最小实现只需两个方法:
vehicleConfigJson():返回 JSON 的资源路径(格式如:/qml/QGroundControl/AutoPilotPlugins/APM/VehicleConfig/MyFeature.VehicleConfig.json);setupSource():返回生成的 QML URL(qrc:/qml/QGroundControl/AutoPilotPlugins/APM/MyFeatureComponent.qml)。
其余纯虚方法(name、iconResource、requiresSetup、setupComplete、summaryQmlSource、setupCompleteChangedTriggerList)按实际页面语义实现,可参照 PowerComponent 对 BAT1_SOURCE 等参数的 setupComplete 判定逻辑(PowerComponent.cc)。
步骤 3:在 AutoPilotPlugin 子类中注册组件
在对应插件的 AutoPilotPlugin 子类(PX4AutoPilotPlugin.cc / APMAutoPilotPlugin.cc)中实例化该组件并挂入组件列表,同时加入 qobject_cast 的类型分支以便状态查询。
步骤 4:把生成文件名加入 _config_generated_qml_names
在插件 CMakeLists.txt 的 _config_generated_qml_names(PX4 为 _apm_config_generated_qml_names)列表中加入新页面输出的 QML 文件名(如 MyFeatureComponent.qml)。该列表是显式枚举的,忘记添加会导致生成器产出校验失败或模块打包不完整;同时把 JSON 文件加入 qt_add_qml_module 的 RESOURCES,把 QML 文件名加入 QML_FILES。
步骤 5:构建
CMake 会在 configure 阶段自动重跑生成器:
cmake --build build --config Debug --target GenerateConfigQmlAPM # 或 GenerateConfigQmlPX4
由于 file(GLOB ... CONFIGURE_DEPENDS) 与 CMAKE_CONFIGURE_DEPENDS 的存在,改动 JSON、生成器 .py 或模板 .j2 后重新运行 cmake 配置即可触发重新生成;如需快速预览单个页面,也可直接调用:
python3 tools/generators/config_qml/generate_pages.py \
--pages-dir src/AutoPilotPlugins/APM/VehicleConfig \
--output-dir /tmp/generated \
--dry-run
生成与运行时行为深挖
渲染管线:从 PageDef 到 QML 文件
emit.py 的 generate_config_page_qml() 是渲染主函数,流程为:
_propagate_optional(page):把params中非 required 的参数所对应的控件自动标记为optional,避免内联fact:绑定在缺少参数的机型上报错(model.py);- 依次生成 repeat 计数属性、section 可见性条件、搜索词表、可翻译词表;
- 按 section 类型分派:
repeat→_qml_repeat_section,component→_qml_component_section,否则 →_qml_generated_section; - 套用 templates/page.qml.j2 产出完整 QML。
生成的 QML 顶层结构为 SetupPage 包裹一个 Item,内含 controllerType 指定的控制器实例、constants/params/bindings 属性、repeat 计数属性、sectionMatchesFilter() 与 sectionVisible() 两个 JS 函数,以及由 ConfigSection 组成的 ColumnLayout(见 templates/generated_section.qml.j2)。
搜索过滤机制
页面顶部的过滤输入框通过 sectionMatchesFilter(sectionId, searchKey) 工作(templates/page.qml.j2):每节维护两组词表——_searchTerms(英文小写原文)和 _translatableSearchTerms(交给 qsTranslate 在运行时翻译成用户语言),搜索词来自 section 标题、keywords、控件 label 与参数名(model.py)。repeat 生成的每个实例以其未翻译的基础标题作为 searchKey,保证"Battery 1/Battery 2"都能被同一组关键词命中。
repeat 的 QML 侧实现
repeat section 在 QML 中展开为 Repeater { model: _<safe>Count }(templates/repeat_section.qml.j2),每个 delegate 是带索引属性的 ConfigSection:
- 实例计数由属性初始化器中的
while循环探测参数得到,默认模板见 templates/repeat_count_default.qml.j2; _fullParamName(postfix)把控件里的参数后缀拼成完整参数名("BAT" + _indexStr + postfix);_sectionId属性在实例数大于 1 时拼接"<title> <索引>",与 C++ 侧sectionIds()的展开结果保持一致——这是侧边栏与页面内容能够对应上的关键契约。
校验与防御
生成器的健壮性来自三层防御:
- 未知键拒绝:model.py 用一组
_ALLOWED_*_KEYS白名单逐层校验,杜绝 JSON 拼写错误静默吞掉; - QML 安全字符串:title、label、keyword 都会经过
require_qml_safe_string,包含引号、反斜杠、换行的字符串直接报错(测试类TestQmlUnsafeStringRejection覆盖); - 语义约束:
enableParam缺disabledParamValue报错、repeat title 含{index}报错、enumValues 的 value 为布尔或非数字/字符串类型报错等。
这些校验行为均有对应的 pytest 用例,见 tools/tests/test_config_qml_generator.py 的 TestUnknownKeyRejection、TestQmlUnsafeStringRejection 等测试类,是理解 Schema 边界最直接的"可执行文档"。
编写 VehicleConfig 的注意事项
以下注意事项来自原文档并结合源码校验逻辑展开:
- 键顺序:
constants、params、bindings应放在sections之前,因为 sections 中的表达式会引用它们,先定义便于阅读维护; - 常量为原生数字:constants 应使用 JSON 原生数字而非字符串(写
0而不是"0")。VehicleComponent::_ensureSectionsCached()中resolveConstantInt虽兼容字符串,但 QML 侧常量会直接内联进表达式,字符串可能造成类型不匹配; - CMake 名单必须同步:
_config_generated_qml_names(PX4 为_apm_config_generated_qml_names)是显式列表,新页面漏加会导致集成不完整,且qgc_add_qml_codegen会在 configure 阶段以FATAL_ERROR校验声明与产物的一致性; - repeat 内参数用后缀:repeat section 内的控件
param一律写后缀(如_SOURCE),showWhen表达式里用_fullParamName()拼全名,切勿写死带索引的完整参数名; - enableParam/disabledParamValue 必须成对:二者缺一不可,只写一个会在 JSON 加载时直接抛出
ValueError(model.py)。
小结
QGroundControl 的 VehicleConfig 生成机制是一条"声明式 JSON → 构建期代码生成 → C++ 组件运行时驱动"的完整链路:JSON 定义决定页面的内容与布局,Python 生成器在构建期把它翻译为 QML,VehicleComponent 基类在运行时复用同一份 JSON 驱动侧边栏的展开、过滤与实时更新。对开发者而言,掌握 tools/generators/config_qml/README.md 中的 Schema,对照 Power.VehicleConfig.json、Safety.VehicleConfig.json、APMPower.VehicleConfig.json 三份范例,再结合 tools/tests/test_config_qml_generator.py 的校验用例,即可在保持 UI 风格统一的前提下,以最低成本为 PX4 或 ArduPilot 新增配置页面。