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
\ingroup qmllint-warnings-and-errors
6
7
\title Loose equality comparison type coercion
8
\brief [equality-type-coercion] Using loose equality comparison operators may coerce values.
9
10
\qmllintwarningcategory equality-type-coercion
11
12
\section1 Loose equality comparison type coercion
13
14
\section2 What happened?
15
Two values were compared for equality using the loose comparison operators.
16
17
\section2 Why is that bad?
18
The loose comparison operators can coerce values to a different type before
19
checking for equality. This can lead to unexpected results.
20
21
\section2 Example
22
Here is an example with a list of Rectangles and a TextInput. When the user
23
enters a number, the Rectangle at that index is highlighted.
24
The code has a flaw. If the input is empty, the first rectangle is highlighted
25
in red, because "" == 0.
26
\qml
27
import QtQuick
28
29
Item {
30
TextInput {
31
id: input
32
}
33
Repeater {
34
model: 3
35
Rectangle {
36
// first rectangle is red on empty input
37
color: input.text == index ? "red" : "blue"
38
}
39
}
40
}
41
\endqml
42
In general, use the strict comparison operators \c{===} and \c{!==}.
43
Even if you are aware of the coercion, it is still recommended to use explicit
44
casts and strict comparisons instead.
45
\qml
46
import QtQuick
47
48
Item {
49
TextInput {
50
id: input
51
}
52
Repeater {
53
model: 3
54
Rectangle {
55
// check inputs, use explicit casts, and strict equality operators
56
color: input.text.length !== 0
57
&& Number(input.text) === index ? "red" : "blue"
58
}
59
}
60
}
61
\endqml
62
*/
qtdeclarative
src
qml
doc
src
qmllint
equality-type-coercion.qdoc
Generated on
for Qt by
1.16.1