'How to set a QTableWidget to consistently scroll to bottom during live data input

I currently have a working GUI that implements a QTableWidget (not to be confused with a QTableView). This QTableWidget takes in a live stream of data and I want to have it so the vertical scroll bar that appears defaults to the bottom. I have tried several methods including setToBottom() with no success. I understand that there are many ways to do this by using a QTableView, however I am looking for a way in which to do this via QTableWidget.



Solution 1:[1]

You can use self.ui.tableWidget.scrollToBottom just after inserting a new item. But it does not always work as expected. It moves the scroll bar only to the beginning of the last row inserted which is not always necessarily the bottom of the table because sometimes the height of the last row inserted is really large.

So i think this is a good method to always scroll to the bottom of tablewidget :

item = self.ui.tableWidget.item(lastIndex, 0)
self.ui.tableWidget.scrollToItem(item, QtGui.QAbstractItemView.PositionAtTop)
self.ui.tableWidget.selectRow(lastIndex)

scrollToItem scrolls the view to ensure that the item is visible. The hint parameter specifies more precisely where the item should be located after the operation. Here PositionAtTop scrolls to position the item at the top of the viewport and lastIndex is the index of the last item inserted to the table.

Solution 2:[2]

As far as I remeber layout invalidation is delayed in Qt views. So you cannot scroll to some element or to bottom just after you added data. You should delay scrolling with timer. It is a bit dirty but the only working way I came up with

Like this (C++ code)

void getData()
{
    addDataToWidget();
    QTimer::singleshort(10, widget, SLOT(scrollToBottom());
}

Solution 3:[3]

If you are using PyQt6, you can use:

self.tableWidget.setItem(row, column, itemMeasVal)
self.tableWidget.scrollToItem(itemMeasVal,QtWidgets.QAbstractItemView.ScrollHint.EnsureVisible) # This is for the bar to scroll automatically and then the current item added is always visible 

Scrolls the view if necessary to ensure that the item is visible. The hint parameter specifies more precisely where the item should be located after the operation. You can check more here: https://doc.qt.io/qtforpython/PySide6/QtWidgets/QTableWidget.html https://doc.qt.io/qtforpython/PySide6/QtWidgets/QAbstractItemView.html#PySide6.QtWidgets.PySide6.QtWidgets.QAbstractItemView.scrollTo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nejat
Solution 2
Solution 3 Olympia Gallou