c++qtqtreeviewqmodelindex

List of visible items from QTreeView


What's the best way to get the list of the currently visible items displayed by a QTreeView? And is it possible to get notifications when it changes?

The data for my model can change asynchronously of the application (data comes from hardware registers). Refreshing that data can be slow, so I want to periodically refresh in a dedicated thread. I don't want to refresh all the items as it would be very inefficient, just the visible ones.

I am aware of this, but in my case the data changes asynchronously so I cannot refresh the items only when setData() is called.


Solution

  • It might be easier to just ignore the view and focus on the model.

    You can model it on a simple refresh-ahead cache: .data() returns the last known value, but also schedules an update. Since the view will call model.data(index)

    This can form a loop to poll the visible items. And the view will stop calling .data() when the cell is not visible, terminating the loop. You should also take into account that data() can be called outside this loop, so nothing breaks.

    Possible sequence

    UI

    1. Cell comes into view
    2. View calls model.data(cell, Qt::DisplayRole):
      • add cell to set of scheduled indexes (if not already scheduled)
      • return old or default data
    3. Data updated asynchronously, emit dataChanged()
    4. Either cell is in view, and the view will call model.data() again - loop back to step 2, or the cell isn't visible and the sequence ends here.

    Data Thread

    1. Every X ms update all scheduled indexes (clearing the set).

    This will fulfill your requirement of continuously/asynchronously polling the visible model items.