Question

I have a QMainWindow with two QTableViewson it. Each QTableView has its own QSqlRelationalTableModel. I am using OnManualSubmit as the edit strategy for both models. Both models hit the same database, and are populated using setTable (each hits a different table), followed by select().

The model for the second table is set up with appropriate calls to setRelation to link it to the table used to populate the first model. On the second (child) view, I call view->setItemDelegate(new QSqlRelationalDelegate(view));

Everything seems to work great: data that appears in the first view is listed in a drop-down in the appropriate field of the second view.

My issue: when I add, edit, or delete a record to the first (parent) view and save it to the database, how should I refresh the second view so that the drop-down is accurate?

There may be unsaved edits in the second (child) view, and I don't want to lose those, nor do I want to save them yet. I just want the drop-down list to be updated appropriately.

I tried child_model->relationModel(fk_col)->select(); and that works, but child_model->relationModel(fk_col)->columnCount(); indicates that the select is operating on all the fields of the parent table, which seems like unnecessary pessimization.

This is my first attempt using <QtSql> and QTableView so I may be missing something fundamental. Maybe there is a way to use the same model for both views, and the refresh happens automatically? What is the appropriate way for child view drop-downs to be refreshed?

Was it helpful?

Solution

The query executed by QSqlRelationalTableModel doesn't contains the foreign keys anymore.

For example with this db structure:

CREATE TABLE countries (id, name);
CREATE TABLE cities(id, name, id_country);

The query would look like this:

SELECT id, name, country_name FROM cities 
    LEFT JOIN countries ON id_country = countries.id;

Which means, the query has to be re-executed for the table to be updated, if the joined table changes.

To refresh automatically, I guess you would have:

  • to use regular QSqlTableModel to keep the actual foreign keys in the model,
  • to write a QAbstractItemDelegate class to display the mapped value and to create the QComboBox editor.
  • to trigger a repaint of the mapped column area on the view whenever the first model changes.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top