Remove row from QTableView
-
I have a
QTableView
and customQStandardItemModel
class implementation. In the application, user is allowed to select the rows and delete them by pressing the button.I implemented delete, which seems to work fine, but I am not sure if this is the right and recommended way in Qt.
Function called when button is pressed. I am interested in rows only. I get list of
ModelIndex()
, that I pass to custom model for delete operation:def delete_selected_item_entries(self): selecteditems = self.ui.tableView_items.selectionModel().selectedRows() self.model_items.remove_rows_list([item.row() for item in selecteditems])
In my model, I have implemented
remove_rows_list
. Idea is to first sort the indexes from largest to smallest, and then callbegin/endRemoveRows
functions for each index. Indexes may not be in a sequence.My model data array is in
table_data
variable.# Remove rows def remove_rows_list(self, list_of_rows:list[int]): # Sort indexes from largest to smallest, # to delete array from end to beginning. # This is to avoid array data shifting when deleting element list_of_rows = sorted(list_of_rows, reverse = True) # We do not expect big list, so we can call begin/end often... for index in list_of_rows: self.beginRemoveRows(QModelIndex(), index, index) del self.table_data[index] self.endRemoveRows()
Is this the correct way, or is there better Qt suggested way?
-
Hi,
You should only need to re-implement the removeRows method. There's no need to reinvent the wheel here.
However, why are you using QStandardItemModel as base model since you want to manage your own data structure ?
-