Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("1.db");
if (!db.open())
{
qDebug() << "Failed to connect to database:" << db.lastError().text();
return ;
}
QSqlQuery query;
query.exec("create table mytable(id int, name QString, sex QString)");
pTableModel = new QSqlTableModel(ui->tableView, db);
pTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);// 编辑策略
pTableModel->setTable("mytable");
// pTableModel->setFilter("name = '666'");
// pTableModel->setSort(pTableModel->fieldIndex("id"), Qt::AscendingOrder); // 增序排序
if (!(pTableModel->select()))
{
if (pTableModel->lastError().isValid())
{
qDebug() << "Error:" << pTableModel->lastError();
}
}
pTableModel->setHeaderData(pTableModel->fieldIndex("id"), Qt::Horizontal, "工号");
pTableModel->setHeaderData(pTableModel->fieldIndex("name"), Qt::Horizontal, "姓名");
pTableModel->setHeaderData(pTableModel->fieldIndex("sex"), Qt::Horizontal, "性别");
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
ui->tableView->setModel(pTableModel); // 设置数据模型
/*
theSelection = new QItemSelectionModel(pTableModel); // 关联选择模型
ui->tableView->setSelectionModel(theSelection); // 设置选择模型
dataMapper = new QDataWidgetMapper();
dataMapper->setModel(pTableModel); // 设置数据模型
dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
dataMapper->addMapping(ui->lineEdit_ID, pTableModel->fieldIndex("id"));
dataMapper->addMapping(ui->lineEdit_Name, pTableModel->fieldIndex("name"));
dataMapper->addMapping(ui->lineEdit_sex, pTableModel->fieldIndex("sex"));
*/
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_add_clicked()
{
// 插入记录
QSqlRecord record = pTableModel->record();
record.setValue("id", ui->lineEdit_id->text().toInt());
record.setValue("name", ui->lineEdit_name->text());
record.setValue("sex", ui->lineEdit_sex->text());
bool ret = pTableModel->insertRecord(pTableModel->rowCount(), record); // -1 表示在表的末尾插入新记录
if (!ret)
{
qDebug() << "insertRecord Error:" << pTableModel->lastError();
}
ret = pTableModel->submitAll();
if (!ret)
{
qDebug() << "insertRecord Error:" << pTableModel->lastError();
}
}
void Widget::on_pushButton_save_clicked()
{
pTableModel->submitAll();
}
void Widget::on_pushButton_del_clicked()
{
bool ret = pTableModel->removeRow(pTableModel->rowCount()-1); //删除最后一行
if(!ret)
{
qDebug() << "删除数据失败";
return;
}
ret = pTableModel->submitAll();
if (!ret)
{
qDebug() << "insertRecord Error:" << pTableModel->lastError();
}
}
demo下载:点击跳转
运行效果:
觉得有帮助的话,打赏一下呗。。