qt - 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()
}
}
解决方案
有原因eval
被认为是不安全的,但这里甚至不需要它。只需使用Repeater
.
Column {
Repeater {
model: 10
CheckBox {
onCheckStateChanged: {
checkedlist[index] = checkState
}
}
}
}
推荐阅读
- terraform - 复杂数据类型map(object)的关键是什么
- java - 非易失性变量是否需要同步?
- cplex - 在 OPL 中根据 id 组合两个元组
- python - 熊猫:比较两个单独的数据框,找到一列的交集,但使用另一列中的值来确定要保留哪个数据框?
- flutter - 参数类型“上下文”不能分配给参数类型“BuildContext” - Flutter
- jquery - D3 动画未更新
- c# - 如何在 Visual Studio 2019 社区版上禁用 Jit 对话框
- django - 使用 Django 显示搜索项目的数据
- ruby-on-rails - 复杂的 Active Record 关系
- r - R- 布尔值:for-loop(向量中的向量)