You can use QSqlTableModel
for this.
As the doc says, it can be used quite easy:
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("employee");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
QTableView *view = new QTableView;
view->setModel(model);
view->hideColumn(0); // don't show the ID
view->show();
I guess I need to create a model class for each of my tables?
Yes, one model represents one sql table.
citiesTableModel constructor will fetch data from the table in the database?
QSqlTableModel
will do it for you:
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("employee");
model->select();
Do I need to subclass QTableView for every different model?
No, you don't. A single QTableview
can display any model you set using setModel
.
Finnaly, I guess that view.setData and view.setModel need to be reimplemented? setModel will loop over each model rows to build the QTableView, and setData will do proper query to add new data in the model?
Depending on the edit strategy you set using setEditStrategy
, the changes will be commited as your are editing table cells, or after you submit them using submitAll
.
Also, you may want to take a look at the QDataWidgetMapper
. It can map your model data to different widgets and track the changes you are doing editing those widgets.