簡體   English   中英

QStandardItemModel - 刪除一行

[英]QStandardItemModel — delete a row

我在QTableView使用QStandardItemModel 這里我在主窗口中有兩個按鈕和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());

我的建議是 - 你試圖在沒有選擇的情況下刪除行。 試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM