En esta página

Coerción de tipo de comparación de igualdad floja

Esta categoría de advertencia se escribe [equality-type-coercion] por qmllint.

Coerción de tipo de comparación de igualdad floja

¿Qué ha ocurrido?

Se ha comparado la igualdad de dos valores utilizando operadores de comparación poco precisos.

¿Por qué es malo?

Los operadores de comparación sueltos pueden coaccionar valores a un tipo diferente antes de comprobar la igualdad. Esto puede conducir a resultados inesperados.

Ejemplo

Este es un ejemplo con una lista de Rectángulos y un TextInput. Cuando el usuario introduce un número, el Rectángulo en ese índice es resaltado. El código tiene un fallo. Si la entrada está vacía, el primer rectángulo se resalta en rojo, porque "" == 0.

import QtQuick

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

En general, utilice los operadores de comparación estricta === y !==. Incluso si usted es consciente de la coerción, se recomienda utilizar moldes explícitos y comparaciones estrictas en su lugar.

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.