块作用域变量声明
qmllint 将此警告类别拼写为[block-scope-var-declaration] 。
在块作用域内使用 var 声明了变量
发生了什么?
在块作用域内(例如在 while 循环的 body 中)使用 var 声明了 JavaScript 变量。虽然看起来该变量似乎只能在该作用域内使用,但实际上它可以在作用域外被访问,因为它会被提升到最内层函数或 QML 绑定的作用域中。
这有什么问题?
此类变量的作用域难以追踪,可能会造成混淆,并可能意外遮蔽其他变量。
示例
import QtQuick
Item {
id: root
property int count: 0
function countItems() {
let sum = 0
{
var count = root.children.length
sum += count
}
// ... more additions to sum
count = sum // modifies the function local variable, not root.count
}
}要解决此警告,请改用 `let` 或 `const`,或者直接在函数作用域内声明该变量。
© 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.