关于在条件中使用赋值的警告

此警告类别由 qmllint 拼写为[warn-assignment-in-condition]

关于在条件中使用赋值的警告

发生了什么?

您在if-condition 中使用了赋值。

为什么这样做不好?

这通常是一个错误,应该使用比较。如果是有意为之,通常也会引起混淆。

示例

import QtQuick

Item {
    id: root
    Component.onCompleted: {
       // mistake: should have been a comparison
       if (width = height)
           console.log("A square")
       let mypoint = Qt.point(1,2)
       let hit = false
       // intentional, but possibly misleading
       if (hit = root.contains(myPoint))
           console.log("hit")
       root.enabled = hit
    }
}

要修复此警告,如果是错误的,将赋值改为比较。否则,将赋值包入括号中,以表明这是有意为之。

import QtQuick

Item {
    id: root
    Component.onCompleted: {
       // fixed
       if (width === height)
           console.log("A square")
       let mypoint = Qt.point(1,2)
       let hit = false
       // intentional
       if ((hit = root.contains(point)))
           console.log("hit")
       root.enabled = hit
    }
}

© 2025 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.