How to keep an item view scrolled to the bottom wh

2019-07-14 06:15发布

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条回答
Root(大扎)
2楼-- · 2019-07-14 06:57
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(); });
查看更多
登录 后发表回答