Search code examples
sqlqtqt4qtreeviewqabstractitemmodel

QTreeView and QSqlQueryModel -- loading children as needed from sql database


I have a following problem.

I'm trying to implement a model for my QTreeView that would load dynamically data from sql table.

Table looks like this:

CREATE TABLE xcmObjects
(
   id                       INT               AUTO_INCREMENT PRIMARY KEY NOT NULL,
   id_parent                INT               DEFAULT 0 NOT NULL ,
   title                    TEXT

);

id_parent contains id of a parent record - so they form a structure.

I'd like my model to load data from this table only when needed. In other words I don't want to load the full structure into memory, instead I wan't to read children of only those nodes that have been opened by the user.

QSqlQueryModel and QSqlTableModel seem to work only for flat tables.

I think that one solution to this problem would be to implement custom QAbastractItemModel class and inside store seperate QSqlQueryModel instances for each open node (including the top level invisible parent). And then rewrite each method and forward requests to apropriate models.

Maybe there is some simpler solution ? :-)

Thanks for help.


Solution

  • I don't think it would be too difficult to work through a subclass of QAbstractItemModel to do this. Your top level would be all items in the table where parent_id is 0. Store the ID of each item as the internal data for the QModelIndex classes, and then you can use the parent index passed in to various functions to construct new queries for the data.