简体   繁体   English

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

[英]Removing QStandardItems from QStandartItemModel in QListView in PyQt4 using a loop

I have a QListView displaying several QStandardItems that are contained in a QStandardItemModel . 我有一个QListView,它显示QStandardItemModel中包含的几个QStandardItems 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 ) when clicked: 单击时,我有一个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)

So the problem is, as I stated in the code comments, that only the first checked item of the list is removed. 因此,问题是,如我在代码注释中所述,仅列表中的第一个选中项被删除。 I know that the last for loop loops as many times as the number of checked boxes, so removeRow is being called the correct number of times. 我知道最后一个for循环的循环次数与复选框的数目相同,因此removeRow被称为正确的次数。

How can I fix this problem? 我该如何解决这个问题?

Edit: 编辑:

self.upload_list_model is the QStandardItemModel self.upload_list_model是QStandardItemModel

Edit2: EDIT2:

I have realized that the problem lies in the last loop: it changes the row indexes in every loop making the rows_to_remove list useless for the next removals. 我已经意识到问题出在最后一个循环中:它改变了每个循环中的行索引,从而使得rows_to_remove列表在下一次移除时无用。 So I was wrong when I said that the loop only removes one item from the model, it always tries to remove the correct amount of items, but in my testings I tried to remove the second and the last item (for example), and after removing the second one, the last item was no longer in the row the loop tried to remove. 因此,当我说循环仅从模型中删除一个项目时,我总是错的,它总是尝试删除正确数量的项目,但是在测试中,我尝试删除第二个和最后一个项目(例如),然后删除第二个,最后一个项目不再在循环尝试删除的行中。

Now I understand the problem, but I still do not know how to make the row indexes change throughout the loop. 现在,我了解了问题所在,但是我仍然不知道如何在整个循环中更改行索引。 Any suggestions for this? 有什么建议吗?

I managed to solve the problem with this recursive method: 我设法用这种递归方法解决了这个问题:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM