问题
When appending items at the end of a model shown by a QAbstractItemView
, I wish to keep the view at the bottom of the data, showing the most recent added items. The default behavior is to retain the most recently displayed item's position, but not to scroll if we were at the bottom.
What would be the magic needed to keep the view at the bottom if the user has previously scrolled it all the way to the bottom?
回答1:
QListView view;
bool viewAtBottom = false;
Before an item is added, check if the view is scrolled all the way to the bottom.
connect(view.model(), &QAbstractItemModel::rowsAboutToBeInserted,
&view, [&] {
auto bar = view.verticalScrollBar();
viewAtBottom = bar ? (bar->value() == bar->maximum()) : false;
});
After an item is inserted, scroll to the bottom if the view was previously at the bottom before the item got added.
connect(view.model(), &QAbstractItemModel::rowsInserted,
&view, [&]{ if (viewAtBottom) view.scrollToBottom(); });
来源:https://stackoverflow.com/questions/38796507/how-to-keep-an-item-view-scrolled-to-the-bottom-when-items-are-added