Remove row from QTableView
-
I have a
QTableViewand customQStandardItemModelclass 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/endRemoveRowsfunctions for each index. Indexes may not be in a sequence.My model data array is in
table_datavariable.# 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 ?
-
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 ?
-
@SGaist Thanks. Is the
removeRowsa function view is supposed to call directly, or is this function called through anyQTableViewAPI?I agree that
QAbstractItemModelmakes more sense indeed. -
@tilz0R not necessarily no but it's a standard method that can be called from any class manipulating the model.
-
T tilz0R has marked this topic as solved on