Qt Delete selected row in QTableView

I want to delete the selected row from the table when I click the delete button.

But I can not find anything about how to remove lines in the Qt documentation. Any ideas?

Image

+7
source share
3 answers

To do this, you can use the functionality of bool QAbstractItemModel::removeRow(int row, const QModelIndex & parent = QModelIndex()) .

Here you can find an example for all of this.

Also, here is a quote from this documentation:

removeRows ()

Used to remove rows and data items that they contain from all types of models. Implementations should call beginRemoveRows () before inserting new columns into any underlying data structures and immediately call endRemoveRows ().

The second part of the task is to connect the signal with the pressed button to the slot that performs the removal for you.

+14
source

You can use another method by deleting a row from the database, then clear the model and fill it again, this solution is also safe when deleting several rows.

+1
source

If you removeRow() multiple lines, you may run into some difficulties using removeRow() . This works with row indexes, so you need to delete rows from bottom to top so that row indices do not move when they are deleted. This is how I did it in PyQt, I don’t know C ++, but I think it is very similar:

 rows = set() for index in self.table.selectedIndexes(): rows.add(index.row()) for row in sorted(rows, reverse=True): self.table.removeRow(row) 

Works great for me! However, one thing you should know: in my case, this function is called when the user clicks on a specific cell (the button has an β€œX” on it). Unfortunately, when they click on this button, it deselects the line, which then prevents it from being deleted. To fix this, I just grabbed the sender line and added it to the "remove_list" at the very beginning, before the "for loop". It looks like this:

 remove_list.append(self.table.indexAt(self.sender().pos()).row()) 
+1
source

Source: https://habr.com/ru/post/954624/


All Articles