QString dbName = "myDatabase.db";
bool isexists = info.exists();
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbName);
QString sql = "create table student(studentID int, name text, "
"class text, chinese float, math float, "
"english float, physics float, sports float, total float);";
bool ret = query.exec(sql);
QMessageBox::warning(this,"警告","创建数据库失败!",QMessageBox::Yes);
model = new QSqlTableModel(this, db);
model->setTable("student");
model->setHeaderData(0, Qt::Horizontal, QVariant("学号"));
model->setHeaderData(1, Qt::Horizontal, QVariant("姓名"));
model->setHeaderData(2, Qt::Horizontal, QVariant("班级"));
model->setHeaderData(3, Qt::Horizontal, QVariant("语文"));
model->setHeaderData(4, Qt::Horizontal, QVariant("数学"));
model->setHeaderData(5, Qt::Horizontal, QVariant("英语"));
model->setHeaderData(6, Qt::Horizontal, QVariant("物理"));
model->setHeaderData(7, Qt::Horizontal, QVariant("体育"));
model->setHeaderData(8, Qt::Horizontal, QVariant("合计"));
ui->tableViewShow->setModel(model);
void Widget::on_btnOK_clicked()
void Widget::on_btnAdd_clicked()
model->insertRow(model->rowCount());
void Widget::on_btnCancel_clicked()
void Widget::on_btnSelect_clicked()
void Widget::on_btnAscending_clicked()
QModelIndex index= ui->tableViewShow->currentIndex();
model->sort(index.column(), Qt::AscendingOrder);
ui->tableViewShow->setCurrentIndex(index);
void Widget::on_btnDescending_clicked()
QModelIndex index= ui->tableViewShow->currentIndex();
model->sort(index.column(), Qt::DescendingOrder);
ui->tableViewShow->setCurrentIndex(index);
void Widget::on_btnDelete_clicked()
int selectRow = ui->tableViewShow->currentIndex().row();
model ->removeRow(selectRow);
void Widget::on_btnAffair_clicked()
model->database().transaction();
int selectRow = ui->tableViewShow->currentIndex().row();
model->removeRow(selectRow);
bool ret = model->submitAll();
int ret = QMessageBox::information(this,"删除确认","是否确认删除当前行",
QMessageBox::Yes | QMessageBox::No);
if(ret == QMessageBox::No){
model->database().rollback();
model->database().commit();