Qt Delete selected row in QTableView

2019-04-24 16:33发布

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

3条回答
叼着烟拽天下
2楼-- · 2019-04-24 17:18

You can use another way by deleting the row from database, then clear the model and fill it again, this solution is also safe when you are removing multiple rows.

查看更多
乱世女痞
3楼-- · 2019-04-24 17:18

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, reversed=True):
    self.table.model().removeRow(row, self.table.rootIndex()) # you'll need to provide the parent. In this case I'm giving the example of a table with no sub-children.

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:

remove_list.append(self.table.indexAt(self.sender().pos()).row())
查看更多
Explosion°爆炸
4楼-- · 2019-04-24 17:26

You can use the bool QAbstractItemModel::removeRow(int row, const QModelIndex & parent = QModelIndex()) functionality for this.

Here you can find an example for all this.

Also, here is an inline quote from that documentation:

removeRows()

Used to remove rows and the items of data they contain from all types of model. Implementations must call beginRemoveRows() before inserting new columns into any underlying data structures, and call endRemoveRows() immediately afterwards.

The second part of the task would be to connect the button's clicked signal to the slot executing the removal for you.

查看更多
登录 后发表回答