Search code examples
c++qtqtreeviewmodel-view

Loading data in QTreeView async


I have a really big tree structure and I cant load the complete tree into Ram on client side. I am using Qt's QTreeView.

I want to load the sub elements of an item dynamically when the user expands the element.

Is there some signal that triggers when the user opens an item in the tree?

I am using the tutorial Simple Tree Model Example. When I do changes to the model the view has also to be updated. And I dont want to loose the focus to avoid user confusion!

sub elements of tree still loading

and after some time (request to the server)...

sub elements of tree finished loading and showing them


Solution

  • You need to implement a subclass of QAbstractItemModel that can process needed amount of data. When an item is expanded in the view, it calls QAbstractItemModel::rowCount to determine children count and then QAbstractItemModel::flags and QAbstractItemModel::data to get children data. If requested data is not available at the moment, you should return placeholder data (i.e. 1 row containing "Loading"), and start a request. When the data is received, emit rowsAboutToBeInserted and rowsInserted signals to notify the view about new data (you should also notify it about removing "Loading" row). The view will then call rowCount, data, and flags methods again, and your model should now provide loaded data. Use QCache to keep last accessed data in memory.