0

I have a Qt project where I have a QStandardItemModel called stockModel. This model is linked to a QTableView called tvStock.

I have a button called btnDelete which has a clicked event set up as follows:

void StockItems::on_btnDelete_clicked()
{
    //delete
}

How do I delete the selected row of tvStock from stockModel?

I assume I can start with this (but I'm not sure how to complete it):

stockModel->removeRow(/* What goes here? */);

Otherwise let me know if I'm completely on the wrong track.

Update:

I found and modified some code that allows to me to delete the row if the entire row's contents are selected:

QModelIndexList indexes = ui->tvStock->selectionModel()->selectedRows();

while (!indexes.isEmpty()) {
    stockModel->removeRows(indexes.last().row(), 1);
    indexes.removeLast();
}

Is there a way this code could be modified to delete the entire row if only one of the row items is selected?

Thanks!

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
  • 1
    Possible duplicate of http://stackoverflow.com/questions/19012450/qt-delete-selected-row-in-qtableview – πάντα ῥεῖ Feb 12 '17 at 10:45
  • The link to that question doesn't solve my problem of how to identify the index of the QTableView. – Barry Michael Doyle Feb 12 '17 at 10:46
  • Call `selectedIndexes` from the view and pass the row number into `removeRow`. The logic used for figuring out which rows to remove in case of different indices selected (for example, if you're allowing single multiple cells to be selected) is up to you. – Daniel Kamil Kozar Feb 12 '17 at 10:47
  • Or, even better, call `selectionModel` on the view and then call `selectedRows` on the returned object. This will give you a list of `QModelIndex` objects representing unique selected rows that you can just loop over and pass the row number directly into `removeRow`. – Daniel Kamil Kozar Feb 12 '17 at 10:52

0 Answers0