逗号
此警告类别由 qmllint 拼写为[comma] 。
请勿使用逗号表达式
发生了什么事?
在 for 循环之外使用了 JavaScript 逗号表达式。
为什么这样做不好?
逗号表达式会降低代码的可读性,并掩盖副作用。
示例
import QtQuick Item { Component.onCompleted: init(config, true), enableLogging(categories), run(1000) // millis }
要修复此警告,可重构代码,为每个操作使用不同的语句。这样,每个副作用都是明确的,而不是作为另一个无关操作的一部分出现:
import QtQuick Item { Component.onCompleted: { init(config, true) enableLogging(categories) run(1000) // millis } }
此外,在逗号表达式出现的情况下,还有一些特殊的注意事项,因为变量被有意捕获用于绑定,例如在下面的代码中,previewOfFirstPage 是一个定义在 C++ 中的函数,它在内部依赖于Config.fontSize :
Text { // This causes the function to re-run when fontSize changes text: Config.fontSize, documentProvider.previewOfFirstPage() }
如果遇到这种情况,请考虑以下方法之一:
- 如果一个函数(如
previewOfFirstPage)依赖于一个属性,最好通过将属性值作为参数传递的方式来明确这种依赖关系。Text { text: documentProvider.previewOfFirstPage(Config.fontSize) }
- 如果由于 API 的原因不希望更改函数签名,可考虑用Q_PROPERTY 代替该函数,以便在 C++ 中修改依赖关系时发出更改通知:
void Config::setFontSize(int fontSize) { if (m_fontSize == fontSize) return; m_fontSize = fontSize; emit fontSizeChanged(); emit previewOfFirstPageChanged(); }
Text { text: documentProvider.previewOfFirstPage }
- 如果无法修改 C++ 实现或添加 QML 依赖项,可使用
qmllint指令来消除警告。包含一个注释,解释在绑定中捕获变量的意图。Text { // This causes the function to re-run when fontSize changes text: Config.fontSize, documentProvider.previewOfFirstPage() // qmllint disable comma }
© 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.