En esta página

Coerción de tipo en la comparación de igualdad «loose»

qmllint escribe esta categoría de advertencia como « [equality-type-coercion] ».

Coerción de tipos en comparaciones de igualdad no estricta

¿Qué ha pasado?

Se han comparado dos valores para determinar si son iguales utilizando los operadores de comparación «loose».

¿Por qué es un problema?

Los operadores de comparación «loose» pueden convertir los valores a un tipo diferente antes de comprobar si son iguales. Esto puede dar lugar a resultados inesperados.

Ejemplo

He aquí un ejemplo con una lista de Rectángulos y un ` TextInput`. Cuando el usuario introduce un número, se resalta el Rectángulo correspondiente a ese índice. 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, utiliza los operadores de comparación estrictos === y !==. Aunque seas consciente de la conversión, se recomienda utilizar conversiones explícitas 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.