Search code examples
pythonpyqtscrollbarpyqt5qtreewidget

Scrolling a QTreeWidget with gestures


I am writing a program in Python 3.5 and PyQt5. I have a QTreeWidget that has a list of items in it. I want to hide the scrollbar and make touch scrolling for it in the vertical direction. This is my code:

    self.category_tree = QTreeWidget(self.framemain)
    self.category_tree.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    self.category_tree.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    self.category_tree.setGeometry(QRect(630, 90, 161, 381))
    self.category_tree.setLayoutDirection(Qt.RightToLeft)
    self.category_tree.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
    self.category_tree.setEditTriggers(QAbstractItemView.NoEditTriggers)
    self.category_tree.setUniformRowHeights(False)
    self.category_tree.setColumnCount(1)
    self.category_tree.setObjectName("category_tree")
    self.category_tree.headerItem().setText(0, "1")
    self.category_tree.setFrameShape(QFrame.NoFrame)
    self.category_tree.header().setVisible(False)
    self.category_tree.header().setSortIndicatorShown(False)
    self.category_tree.setFocusPolicy(Qt.NoFocus)
    self.category_tree.verticalScrollBar().setSingleStep(25)

def checkscroll(self,startx,endx):
    if (startx - endx) >= 25:
    #swipe from right to left
        self.category_tree.verticalScrollBar().setSliderPosition(self.category_tree.verticalScrollBar().sliderPosition()+(25))
    elif (startx - endx) <= -25:
            self.category_tree.verticalScrollBar().setSliderPosition(self.category_tree.verticalScrollBar().sliderPosition()-abs(25))

The problem is that when I swipe on the QTreeWidget to make it scroll it goes to the end or start of the view and doesn't scroll normally.


Solution

  • It looks like you need to use the QScroller class for this. It seems that something like this should work:

    QScroller.grabGesture(self.category_tree.viewport(), QScroller.TouchGesture)
    

    However, I cannot test this myself, so you may need to experiment a bit to get the behaviour you want.

    UPDATE:

    You may also need to change the vertical scroll mode:

    self.category_tree.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)