// 设置一下数据库的表名, 然后直接select()就搞定了. 非常简单.
void initializeModel(QSqlTableModel *model) {
model->setTable("person");
model->setEditStrategy(QSqlTableModel::OnRowChange);
model->select();
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));
}
// 使用model view
QTableView *createView(const QString &title, QSqlTableModel *model) {
QTableView *view = new QTableView;
view->setModel(model);
view->setWindowTitle(title);
return view;
}
QSqlTableModel model(&app, getDatabase());
initializeModel(&model);
QTableView *view1 = createView(QObject::tr("Table Model (View 1)"), &model);
view1->show();