本页

松散的等价比较类型强制

此警告类别由 qmllint 拼写[equality-type-coercion]

松散的等价比较类型强制

发生了什么?

使用松散比较运算符对两个值进行了等价比较。

为什么会这样?

松散比较运算符可以在检查相等性之前将值强制为不同的类型。这会导致意想不到的结果。

示例

下面是一个包含矩形列表和TextInput 的示例。当用户输入一个数字时,位于该索引处的矩形将突出显示。这段代码有一个缺陷。如果输入是空的,第一个矩形会以红色高亮显示,因为"" == 0。

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.