使用循环从 PyQt4 中的 QListView 中的 QStandartItemModel 中删除 QStandardItems

Removing QStandardItems from QStandartItemModel in QListView in PyQt4 using a loop

点击时我有一个 QListView displaying several QStandardItems that are contained in a QStandardItemModel. The items in the model have checkboxes enabled. I have a QPushButton that connects to the following method (that belongs to a class that inherits from QTabWidget):

def remove_checked_files(self):
    rows_to_remove = []  # will contain the row numbers of the rows to be removed.
    for row in range(self.upload_list_model.rowCount()):  # iterate through all rows.
        item = self.upload_list_model.item(row)  # get the item in row.
        if item.checkState() == 2:  # if the item is checked.
            rows_to_remove.append(row)
    for row in rows_to_remove:
        # this loop SHOULD remove all the checked items, but only removes
        # the first checked item in the QListView
        self.upload_list_model.removeRow(row)

所以问题是,正如我在代码注释中所述,只有列表中第一个选中的项目被删除。我知道最后一个 for 循环的循环次数与选中框的数量一样多,因此 removeRow 被调用的次数是正确的。

我该如何解决这个问题?

编辑:

self.upload_list_model 是 QStandardItemModel

编辑2:

我意识到问题出在最后一个循环中:它更改了每个循环中的行索引,使得 rows_to_remove 列表对于下一次删除没有用。所以当我说循环只从模型中删除一个项目时我错了,它总是试图删除正确数量的项目,但在我的测试中我试图删除第二个和最后一个项目(例如),然后删除第二个,最后一个项目不再在循环试图删除的行中。

现在我明白了问题所在,但我仍然不知道如何让行索引在整个循环中发生变化。对此有何建议?

我用这个递归方法解决了这个问题:

def remove_checked_files(self):

    for row in range(self.upload_list_model.rowCount()):
        item = self.upload_list_model.item(row)  # get the item in row.
        if item and item.checkState() == 2:  # if the item is checked.
            self.upload_list_model.removeRow(row)
            self.remove_checked_files()