Proxy Model for Combining Table Models
-
Hello. I have two SQLite tables being used as
QAbstractTableModel
objects in C++ code. I want to use these two models as sources of truth for a newTableView
that will display a combination of the two table models joined together.How can I use a proxy model to combine data from two or more other models, and keep the new model in sync with both parent models? Are there good tutorials or examples anywhere?
Model 1
id data1 data2 data3 other_id Model 2
id (other_id) data3 data4 Model 3 (goal)
id other_id data1 data2 data3 data3 data4 When I filter either model 1 or model 2, I want model 3 to update.
-
Hi,
How do you want to assemble these data ?
Is it some sort of join ? What are the join points ? -
How are the base models updated ?
-
@SGaist Each model (
model1
,model2
) is its ownQAbstractTableModel
made to read data w/QSQLQuery
commands. These models handle- SQL role name extraction
- SQL filtering / sorting
- item selection (
QItemSelectionModel
)
We get data through the last ran
QSQLQuery* _query
, and re-query whenever sorting, filtering, or CRUD operations are applied with the same_query
object. My issue is, I can onlysetModel
once for QML views likeTableView
and I'm not sure how to base one view on two models. -
@Flick
There is nothing out-of-the-box for JOINing Qt models once data read into them. Let alone that I have no idea what restrictions QML might impose. You would have to write code to do that.Since you seem to already re-query on any change in view (e.g. filtering, sorting), would you consider putting the
JOIN
at the SQL side (QSqlQuery
), which is easy to do, and re-reading that too? It will be simpler than what you must add to do the join yourself on theQSql
models in memory. -
@Flick taking the join part aside for a second, you would need a proxy model that announces a number of columns matching the sum of columns of your two tables and the number of row of the biggest of the two tables. Then in the data function you would need to grab the data of the correct model when requested. Qt has such a model but just to concatenate rows of models.
Taking the join back in, you should really consider what @JonB wrote: create the model out of the query from the database. You database will be way better at doing the join than a model in code.
-
If anyone could provide examples of 2+ joined SQL tables in a single QML model, I'd appreciate it. I can't use
QSqlTableModel
because it functions on just one table, but I would like all the functionalityQSqlTableModel
provides (hiding columns, sorting/filtering). -
Use QSqlQueryModel and add the sorting/filtering there or with a QSortFilterProxyModel on top.