このページについて

等価比較における型変換の不整合

qmllint では、この警告カテゴリは「[equality-type-coercion] 」と表記されます。

緩やかな等価比較における型変換

何が起きたのか?

2つの値が、緩い比較演算子を使用して等価性について比較されました。

なぜ問題なのか?

緩い比較演算子は、等価性をチェックする前に値を別の型に強制変換することがあります。これにより、予期しない結果が生じる可能性があります。

例

以下は、RectangleのリストとTextInput を使用した例です。ユーザーが数値を入力すると、そのインデックスにあるRectangleがハイライトされます。このコードには欠陥があります。入力が空の場合、"" == 0 となるため、最初のRectangleが赤くハイライトされてしまいます。

import QtQuick

Item {
    TextInput {
        id: input
    }
    Repeater {
        model: 3
        Rectangle {
            // first rectangle is red on empty input
            color: input.text == index ? "red" : "blue"
        }
    }
}

一般的には、厳密な比較演算子である `=== ` および `!==` を使用してください。型変換の挙動を認識していたとしても、代わりに明示的な型キャストと厳密な比較を使用することを推奨します。

import QtQuick

Item {
    TextInput {
        id: input
    }
    Repeater {
        model: 3
        Rectangle {
            // check inputs, use explicit casts, and strict equality operators
            color: input.text.length !== 0
                   && Number(input.text) === index ? "red" : "blue"
        }
    }
}

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