Basic concept of Qt model/view and QTableView

peterphonic picture peterphonic · Mar 20, 2013 · Viewed 7.5k times · Source

I want to create a software that will browse some database tables and users will be able to edit these tables. Following my reading of this link, I tought that model/view was a good approach for what I need. Look at the following mockup : enter image description here

Knowing this, I have questions to be sure that I understand the concept. Please, tell my if I am in the good direction :

  1. I guess I need to create a model class for each of my tables? (subclassing QAbstractModel). It will look like this :

    class citiesTableModel : public QAbstractItemModel
     {
         Q_OBJECT
     }
    
  2. citiesTableModel constructor will fetch data from the table in the database?

    QAbstractItemModel *model = new citiesTableModel(); //model will contain 2 rows, New York and Seattle
    
  3. Do I need to subclass QTableView for every different model?

    class citiesTableView : public QTableView{}
    
  4. 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?

Thank you very much.

Answer

Kirell picture Kirell · Mar 20, 2013

Basically you have different options:

Either you database is a SQL database. You can use a subclass QSqlTableModel. Otherwise if you want to create your model from scratch you do your own model but I don't see the point. You also have QTableModel with an example.

You don't need to create a model for each of your table, because it is always a tablemodel. The model mostly defines how you can add and remove rows with your specific data.

Concerning the view, you will have to inherit QTableView to add a custom behavior for you rows and cols, such as drag events for instance.

The only element of customization that you need is a delegate for your view or just for a column. It will basically convert a boolean value in your model into a checkbox.

I suggest you look at SpinBox delegate for more precision.

Hope this helps.

Edit:

In the case of a PostgreSQL you can add it in a QsqlDatabase:

 QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
 db.setHostName("acidalia");
 db.setDatabaseName("customdb");
 db.setUserName("mojito");
 db.setPassword("J0a1m8");
 bool ok = db.open();

Then pass the db to the QSqlTableModel. If you need more relational operation, such as fetching fields from a foreign key, you can use:

QSqlRelationalTableModel
QSqlRelationalDelegate