4

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

wollud1969
  • 497
  • 4
  • 13

1 Answers1

3

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))
Avaris
  • 35,883
  • 7
  • 81
  • 72
  • Okay, that works, thank you very much. However, maybe you can help me to understand the difference between `self.connect(self.statsModel, SIGNAL("rowsInserted()"), lambda: QTimer.singleShot(0, self.table.scrollToBottom))` (which does not work) and `self.statsModel.rowsInserted.connect(lambda: QTimer.singleShot(0, self.table.scrollToBottom))` which works. According to your explains I was under the impression that I have to connect to the signal rowsInserted of the model and call scrollToBottom on my view using the singleShot timer. Isn't that what I've done with the first code snippet? – wollud1969 Sep 30 '12 at 07:08
  • @wollud1969: If you're going to use the _old syntax_ you need to give the correct signature for the signal, and the signature for `rowsInserted` is [`rowsInserted(QModelIndex, int, int)`](http://qt-project.org/doc/qt-4.8/qabstractitemmodel.html#rowsInserted). But, that's the beauty of [new syntax](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html). You don't need to care about it :). – Avaris Sep 30 '12 at 08:11
  • Understood! Thank you very much, I will learn about the new syntax and change all my code in this project accordingly. – wollud1969 Sep 30 '12 at 08:18