このページについて

ブロックスコープの変数宣言

この警告カテゴリは、qmllint では「[block-scope-var-declaration] 」と表記されます。

ブロックスコープ内で var を使用して変数が宣言されています

何が起きたのか?

JavaScript の変数が、ブロックスコープ内(たとえば while ループの本体など)で var を使って宣言されています。この変数はそのスコープ内でのみ使用可能に見えるかもしれませんが、実際には、最も内側の関数または 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` を使用するか、関数スコープ内で直接変数を宣言してください。

import QtQuick

Item {
    id: root
    property int count: 0
    function countItems() {
        let sum = 0
        {
            let count = root.children.length
            sum += count
        }
        // ... more additions to sum
        count = sum // modifies the function local variable, not root.count
    }
}

© 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.