首页 > 解决方案 > QML“不要使用'eval'。(M23)”

问题描述

我有 10 个复选框,它们的 id 是从“cb1”到“cb10”。我想在列表中收集它们的状态(然后将其传递给 python)。首先,我想出了非常冗长的函数(每个复选框状态都在“if”语句中,所以函数需要 30 行左右的代码)。我觉得它很糟糕,所以我写了一个“for”循环。但是现在 QtCreator 从标题中向我发出警告。我应该忽略它,还是有更漂亮的方法呢?

main.qml:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    id: window
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    property var checkedlist: []

    function checkedf() {
        checkedlist = []

        var i = 1
        for (i = 1; i < 11; i++) {
            try {
                checkedlist.push(eval("cb" + i + ".checkState"))
            } catch(error) { }
        }

        console.log(checkedlist)
    }


    CheckBox {
        id: cb1
        anchors.top: parent.top
        anchors.topMargin: 0
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb2
        anchors.top: cb1.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb3
        anchors.top: cb2.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb4
        anchors.top: cb3.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb5
        anchors.top: cb4.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb6
        anchors.top: cb5.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb7
        anchors.top: cb6.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb8
        anchors.top: cb7.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb9
        anchors.top: cb8.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
    CheckBox {
        id: cb10
        anchors.top: cb9.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        onCheckStateChanged: checkedf()
    }
}

标签: qtqml

解决方案


有原因eval被认为是不安全的,但这里甚至不需要它。只需使用Repeater.

Column {
    Repeater {
        model: 10

        CheckBox {
            onCheckStateChanged: {
                checkedlist[index] = checkState
            }
        }
    }
}

推荐阅读