QStandardItemModel delete multiple rows without problem – python

I’m coding a reddit bot and created a UI like this:

enter image description here

What I want to do is user selects an account from list, clicks the remove selected account and all checked accounts deleted from list. So here is my code:

def delete_selected_accounts(self):
    print(len(self.account_list))
    for i in range(self.model.rowCount()):

        if self.model.item(i).checkState() == Qt.Checked:
            self.model.removeRow(i)
            self.account_list.pop(i)

However, this code does not work as expected. When I removeRow from a model or pop from the account list, count of lists changes and I’m getting list out of range problem. What can I do to delete selected item without this problem?

>Solution :

Hehe, I answered a similar question yesterday.

You’re iterating over N rows (N being the original number of rows), but along the way, you remove some of the rows. The result? Eventually you’ll try to access self.model.item(N - 1), which would be out of range.

One way to solve this is to iterate from the back (from N - 1 to 0), so that deleted rows don’t affect future rows.

for i in range(self.model.rowCount())[::-1]:
    ...

Here, [::-1] tells range to generate a reverse range. You could write it out explicitly like so: range(self.model.rowCount() - 1, -1, -1). But it looks a bit ugly.

Leave a Reply