本页内容

宽松的相等比较类型强制转换

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.