Problem with scrolling to the bottom of a QListView
Hi all,
Our Symbian Qt4.6.3 app has a view based on a QListView using a QStandardItemModel.
When the data we are displaying is updated, we are resetting and repopulating the model, after which I want to automatically set the scroll position to the bottom of the list.
We have tried using scrollToBottom() and also verticalScrollBar()->setValue(). The trouble is, this doesn't scroll to the bottom if there is a lot of data, only a certain way down the view. Debugging this, I can see that the maximum() value of the scroll bar is limiting the extent to which scrolling is permitted.
It seems that the scroll bar extents are not set by the Qt framework immediately when I populate the model, but that this happens asynchronously some time after. Using a timer to introduce a small delay before calling verticalScrollBar()->setValue() has been found to work, but is a clumsly and proabably unreliable solution.
The best I've come up with is something like this:
Code:
void MyView::ifDataChanged( )
{
int savedScrollPosition = m_listView->verticalScrollBar()->value();
populateModel(); // calls clear() and then a number of appendRow() calls on model
while (m_listView->verticalScrollBar()->value() != savedScrollPosition)
{
QApplication::processEvents();
// need to allow the list view to do its stuff // before we can set the scroll position
m_listView->verticalScrollBar()->setValue(savedScrollPosition);
}
}
Here I'm trying to scroll back to a saved scroll position rather than to the bottom of the view. Obviously I'll have problems if the saved scroll position is too big for the new size of the view. And this loop could lock up the CPU 100% and would be unacceptable in production code. But it works as a proof of concept and does scroll to the desired position.
My question is: is there a better way of doing this? Ideally I'd like to find some kind of signal emitted by the QListView when it has finished the task of working out its layout and setting the scroll ranges, following the repopulation of the model.
Hopefully this is enough information for someone to be able to make helpful suggestions - otherwise my colleague will prepare a stripped down demo app to demonstrate the problem.
Thanks in advance, John
Re: Problem with scrolling to the bottom of a QListView
i would try to connect to the QScrollBar's rangeChanged ( int min, int max ) signal
Re: Problem with scrolling to the bottom of a QListView
Thank you MrDeath, very useful suggestion.
This is going to work. It turns out that the rangeChanged signal can be emitted several times over as the view is built by the Qt framework.
So in my slot I will attempt to scroll to the position I want to be at, then check whether I actually managed to scroll there: if yes, then disconnect from the signal, if no, stay connected and try again next time it is emitted.