Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Delete selected row in QTableView

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

But I can't find anything regarding deleting rows in the Qt documentation. Any ideas?

Image

like image 835
laura Avatar asked Sep 25 '13 18:09

laura


1 Answers

If you are removing multiple rows you can run into some complications using the removeRow() call. This operates on the row index, so you need to remove rows from the bottom up to keep the row indices from shifting as you remove them. This is how I did it in PyQt, don't know C++ but I imagine it is quite 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 perfectly for me! However one thing to know, in my case this function gets called when a user clicks on a specific cell (which has a pushbutton with an 'X'). Unfortunately when they click on that pushbutton it deselects the row, which then prevents it from getting removed. To fix this I just captured the row of the sender and appended it to the "remove_list" at the very beginning, before the "for loops". That looks like this:

rows.add(self.table.indexAt(self.sender().pos()).row())
like image 167
Spencer Avatar answered Oct 15 '22 09:10

Spencer