Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
equality-type-coercion.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2026 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\page qmllint-warnings-and-errors-equality-type-coercion.html
6
\ingroup qmllint-warnings-and-errors
7
8
\title Loose equality comparison type coercion
9
\brief [equality-type-coercion] Using loose equality comparison operators may coerce values.
10
11
\qmllintwarningcategory equality-type-coercion
12
13
\section1 Loose equality comparison type coercion
14
15
\section2 What happened?
16
Two values were compared for equality using the loose comparison operators.
17
18
\section2 Why is that bad?
19
The loose comparison operators can coerce values to a different type before
20
checking for equality. This can lead to unexpected results.
21
22
\section2 Example
23
Here is an example with a list of Rectangles and a TextInput. When the user
24
enters a number, the Rectangle at that index is highlighted.
25
The code has a flaw. If the input is empty, the first rectangle is highlighted
26
in red, because "" == 0.
27
\qml
28
import QtQuick
29
30
Item {
31
TextInput {
32
id: input
33
}
34
Repeater {
35
model: 3
36
Rectangle {
37
// first rectangle is red on empty input
38
color: input.text == index ? "red" : "blue"
39
}
40
}
41
}
42
\endqml
43
In general, use the strict comparison operators \c{===} and \c{!==}.
44
Even if you are aware of the coercion, it is still recommended to use explicit
45
casts and strict comparisons instead.
46
\qml
47
import QtQuick
48
49
Item {
50
TextInput {
51
id: input
52
}
53
Repeater {
54
model: 3
55
Rectangle {
56
// check inputs, use explicit casts, and strict equality operators
57
color: input.text.length !== 0
58
&& Number(input.text) === index ? "red" : "blue"
59
}
60
}
61
}
62
\endqml
63
*/
qtdeclarative
src
qml
doc
src
qmllint
equality-type-coercion.qdoc
Generated on
for Qt by
1.16.1