How to keep an item view scrolled to the bottom when items are added?

心不动则不痛 提交于 2019-12-12 21:16:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!