HatHat556
HatHat556

Reputation: 91

PyQt tablewidget change location of vertical scroll bar

I have a QTableWidget in a window. Currently, the table's scrollbar goes all the way up to the top of the table's headers:

enter image description here

However, I would like the scrollbar to start below the headers, basically moving it down in the y axis. I need it to start at the position of the scroll bar in the image below:

enter image description here

Does anyone have any idea how I could do this?

Upvotes: 0

Views: 1793

Answers (1)

musicamante
musicamante

Reputation: 48260

The simplest solution is to set the geometry of the scroll bar whenever the table resizes:

class Table(QtWidgets.QTableWidget):
    # ...
    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.verticalScrollBar().setGeometry(
            bar.geometry().adjusted(
                0, self.horizontalHeader().height(), 0, 0))

Another similar possibility is to use a scroll bar widget added on top of the scroll bar, but the concept remains almost the same:

class Table(QtWidgets.QTableWidget):
    def __init__(self):
        super().__init__(20, 20)
        self.scrollBarSpacer = QtWidgets.QWidget()
        self.addScrollBarWidget(self.scrollBarSpacer, QtCore.Qt.AlignTop)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.scrollBarSpacer.setFixedHeight(self.horizontalHeader().height())

Do note that in both cases it's mandatory to call the base implementation of resizeEvent() first.

If you don't want to subclass, add an event filter for the table:

class SomeWindow(QtWidgets.QMainWindow):
    def __init__(self):
        # ...
        self.table.installEventFilter(self)

    def eventFilter(self, source, event):
        if source == self.table and event.type() == QtCore.QEvent.Resize:
            # let the table handle the event
            source.event(event)
            source.verticalScrollBar().setGeometry(
                source.verticalScrollBar().geometry().adjusted(
                    0, self.horizontalHeader().height(), 0, 0))
            return True
        return super().eventFilter(source, event)

Upvotes: 3

Related Questions