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!

4
  • 1
    Possible duplicate of stackoverflow.com/questions/19012450/… Feb 12, 2017 at 10:45
  • The link to that question doesn't solve my problem of how to identify the index of the QTableView. Feb 12, 2017 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. Feb 12, 2017 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. Feb 12, 2017 at 10:52

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.