我想在迭代列表时修改列表对象的原始内容。我一直在尝试使用 2 种方法:第一种 -> 使用 for 循环 -> 可以正常工作,但我不确定这是最好的选择,第二种使用QMutableListIterator
完全没有改变对象和我认为也许我没有正确使用它。下面是我的 2 个实现。
第一
QString idNumber = getIDNumberFromSelectedRow(id);
QUuid carId = QUuid(idNumber);
for(int i = 0; i < cars.size(); i++){
Vehicle& current = cars[i];
if(carId == current.getVehicleID()){
addDialog = new AddEditDialog(this);
addDialog->loadVehicleToEdit(current); // i am loading the data from the object i want to edit
addDialog->exec();
if(addDialog->getIsEdited()){ //i'm editing the object
current = addDialog->getVehicleToAdd(); //i'm saving the modifications
current.setVehicleId(carId);
}
}//the object from the list is now modified
}
第二个
QMutableListIterator<Vehicle> iterator(cars);
while(iterator.hasNext()){
Vehicle& current = iterator.next();
if(carId == current.getVehicleID()){
addDialog = new AddEditDialog(this);
addDialog->loadVehicleToEdit(current); //load the object data to modify
addDialog->exec();
if(addDialog->getIsEdited()){//edit the object
current = addDialog->getVehicleToAdd();//save the modifications
iterator.setValue(current);
}
}//the object from the list is not modified at all
}