10-添加、插入与删除记录
11.2.4 添加、插入与删除记录
工具栏上有“添加”“插入”“删除”3个按钮用于记录操作。actRecAppend用于添加记录,其槽函数代码如下:
void MainWindow::on_actRecAppend_triggered()
{//添加记录
tabModel->insertRow(tabModel->rowCount(),QModelIndex());
QModelIndex curIndex=tabModel->index(tabModel->rowCount()-1,1);
theSelection->clearSelection();//清空选择
theSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);
int currow=curIndex.row(); //获得当前行号
tabModel->setData(tabModel->index(currow,0),2000+tabModel->rowCount());
tabModel->setData(tabModel->index(currow,2),"男");
}
QSqlTableModel::insertRow(int row)函数在数据模型的row行前面插入一行记录,如果row大于或等于数据模型的总行数,则在最后添加一行记录。
actRecInsert实现在当前行的前面插入一行,其槽函数代码如下:
void MainWindow::on_actRecInsert_triggered()
{//插入记录
QModelIndex curIndex=ui->tableView->currentIndex();
tabModel->insertRow(curIndex.row(),QModelIndex());
theSelection->clearSelection();//清除已有选择
theSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);
}
actRecDelete用于删除当前记录,其槽函数实现代码如下:
void MainWindow::on_actRecDelete_triggered()
{//删除当前记录
QModelIndex curIndex=theSelection->currentIndex();//获取当前模型索引
tabModel->removeRow(curIndex.row()); //删除一行
}
在插入或删除记录操作,未提交保存之前,tableView的左侧表头会以标记表示记录编辑状态,“*”表示新插入的记录,“!”表示删除的记录。在保存或取消修改后,这些标记就消失,删除的记录行也从tableView里删除。