wollud1969
wollud1969

Reputation: 497

Keep QTableView scrolling to the last row when the model is growing

I've a QTableView in a pyqt application. I continuously append rows to the underlying model. And what I want is the view to continuously scroll to the last, most recent row (is that behavior called "autoscrolling"?). But instead, the view does not scroll at all (automatically) and stays at its position.

Can I enable this autoscrolling behavior somehow or do I need to code something to achieve it?

Cheers, Wolfgang

Upvotes: 4

Views: 5486

Answers (1)

Avaris
Avaris

Reputation: 36715

There is no default autoscrolling feature, but you can get the behavior relatively simple. Your model will emit rowsInserted when you insert/append rows. You can connect to that signal and call scrollToBottom on your view.

There is one problem though. View needs to adjust itself, because it won't put the item at the bottom immediately when rowsInserted fires. Calling scrollToBottom within a QTimer.singleShot solves this because QTimer will wait until there are no pending events (like update of the view).

Assuming the model is stored as self.model and view is self.view, this is how it'll look:

self.model.rowsInserted.connect(self.autoScroll)

and the autoScroll method:

def autoScroll(self):
    QtCore.QTimer.singleShot(0, self.view.scrollToBottom)

Or if you prefer not having a seperate method for this:

self.model.rowsInserted.connect(lambda: QtCore.QTimer.singleShot(0, self.view.scrollToBottom))

Upvotes: 4

Related Questions