假设有数据库文件test.db,有表table(id integer, name nvarchar(20),age integer),且有数条数据。
首先用QTcreator创建一个基于Widget类的窗口,再拖一个tableview到widget中,御桥保存,然后按照如下方法进行:
1.在widget.h中增添头文件:QtSql/qsql.h、QtSql/QsqlDatabase、QtSql/QsqlQuery、QtSql/QsqlQueryModel
2.在.pro工程文件中添加:QT+=sql
3.在widget.cpp中widget的构造函数中添加如下代码:
QsqDatabase db = QsqlDatabase::addDatabase("QSQLITE")
db.setDatabaseName("test.db")
if(!db.open())
{
//错误处理
}
static QSqlQueryModel *model = new QSqlQueryModel(ui->tableview)
model->setQuery(QString("select * from table"))
model->setHeaderData(0,Qt::Horizontal,QObject::tr("编号"))
model->setHeaderData(1,Qt::Horizontal,QObject::tr("姓名"))
model->setHeaderData(2,Qt::Horizontal,QObject::tr("年龄"))
ui->tableview->setModel(model)
db->close()
这样之镇厅猛后,table表里的内容就会显示到tableview中了。
用qsqltablemodel的insetrow()、setdata()、submitall()函数实现增;
officeTable->insertRow(0)
officeTable->setData(officeTable->index(0, 0), row)
officeTable->setData(officeTable->index(0, 1), newWnd->imageFileEditor->currentIndex())
officeTable->setData(officeTable->index(0, 2), newWnd->locationText->text())
officeTable->setData(officeTable->index(0, 3), newWnd->countryText->currentText())
officeTable->setData(officeTable->index(0, 4), newWnd->descriptionEditor->toPlainText())
银肢亏officeTable->submitAll()
用removerow()、submitall()函数实现删;
int officeCount = officeTable->rowCount()
officeTable->removeRow(id)
for(int i = id i < officeCount - 1i++)
{
officeTable->setData(officeTable->index(i, 0), i)
}
officeTable->submitAll()
用QSqlRecord类的setvalue实现改;
QSqlRecord recordCurrentRow = officeTable->record(id)
recordCurrentRow.setValue("id", id - 1)
officeTable->饥咐setRecord(id - 1, recordCurrentRow)
officeTable->submitAll()
用QSqlRecord类的.value进行比较实现查;
int 锋神Dialog::findArtistId(const QString &artist)
{
QSqlTableModel *artistModel = model->relationModel(2)
int row = 0
while (row < artistModel->rowCount()) {
QSqlRecord record = artistModel->record(row)
if (record.value("artist") == artist)
return record.value("id").toInt()
else
row++
}
return addNewArtist(artist)
}用QSqlQueryModel好闭岁肢像不可雀亏以. 用QSqlTableModel或结合QSortFilterProxyModel使用看一下行轿世不行.或者你要重新实现model的sort()函数。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)