QStandardItemModel - 删除一行

时间:2013-06-06 12:00:23

标签: qt qstandarditemmodel

我在QStandardItemModel内使用QTableView。在这里,我有两个按钮&我的主窗口内QTableView。模型内的行会有所不同。 两个按钮用于添加/删除行(测试用例)。

向模型添加行正在运行,ADD button的插槽: -

void MainWindow::on_pushButton_clicked()
{
    model->insertRow(model->rowCount());
}

但是当我从模型中删除一行Delete button的插槽时,我的程序崩溃了: -

void MainWindow::on_pushButton_2_clicked()
{
    QModelIndexList indexes = ui->tableView->selectionModel()->selection().indexes();
    QModelIndex index = indexes.at(0);
    model->removeRows(index.row(),1);

}

请在我的代码中建议我需要更改的内容才能使删除工作正常。

编辑:----

搞定了。

QModelIndex currentIndex = ui->tableView->selectionModel()->currentIndex();
model->removeRow(currentIndex.row());

1 个答案:

答案 0 :(得分:3)

我的建议是 - 你试图在没有选择的情况下删除行。试试这个:

void MainWindow::on_pushButton_2_clicked()
{
    QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
    while (!indexes.isEmpty())
    {
        model->removeRows(indexes.last().row(), 1);
        indexes.removeLast();
    }
}