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

标签 python pyqt qlistview qstandarditemmodel

我有一个QListView显示几个 QStandardItems包含在 QStandardItemModel 中。模型中的项目已启用复选框。我有一个QPushButton单击时连接到以下方法(属于继承自 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()

关于python - 使用循环从 PyQt4 中 QListView 中的 QStandartItemModel 中删除 QStandardItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794385/

相关文章:

python - 使用 docx 包删除表格单元格中的第一行

python - 从 N 个平均值和 N 个西格玛的列表中生成 N 个样本的数组

python - 如何通过 Cassandra python-driver ORM 增加计数器列

c++ - Qt Widget 与树组织的项目

qt - qt4 中的 QListViewItem 发生了什么?

qt - 如何在 QML 中手动填充 ListView?

python - 使用批量提交系统时调试潜在的整数溢出?

python - 如何实现在 Qt Designer 中定义的信号/槽

python - QListWidgetItem 保存列表之间的数据

Python如何从QDateTimeEdit中提取字符串