I have a 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) when clicked:
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.
How can I fix this problem?
Edit:
self.upload_list_model is the QStandardItemModel
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. 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()