本页内容

逗号

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.