SoFunction
Updated on 2024-10-29

pyqt5 QScrollArea set on custom side (any position)

This example is set to the vertical left scroll

The main idea is to use a mid_frame of length 0 and height of the qwidget to be set, and use the moveEvent event of the mid_frame to drive the move of the qwidget.

A rendering of my project:

Code and comments

from  import *
from sys import argv


# Main window
class Main(QMainWindow):
  def __init__(self):
    super().__init__(None)
    (500, 500, 500, 500)

    # Instantiation
     = MainFrame(self)
     = ScrollFrame(self, , 40)

    ()

  def resizeEvent(self, e):
    # resize changes the height of the scroll window to make it the same as itself
    ((), ())

 # Windows that need to be equipped with scroll
class MainFrame(QFrame):
  def __init__(self, father):
    super().__init__(father)
     = father
    (50, 50, 100, 1500)
    
    # Test button
    for i in range(15):
      b = QPushButton(str(i), self)
      (0, i*100, 100, 100)

  # Customize scroll wheel events
  def wheelEvent(self, e):
    if ().y() > 0:
      ((), () + 60)
    else:
      ((), () - 60)
    # Change the value of scroll
    (abs(()))

  def resizeEvent(self, e):
    # resize changes the height of mid_frame to make it the same as itself
    .mid_frame.setGeometry(0, 0, 0, ())


# Window hosting the scrollarea
class ScrollFrame(QFrame):
  def __init__(self, father, parent, pos_x):
    super().__init__(father)
    self.parent_, , self.pox_x = parent, father, pos_x

    self.mid_frame = MidFrame(self)
    self.mid_frame.setGeometry(0, 0, 0, self.parent_.height())

     = QScrollArea()
    # Instantiate the verticalbar for changing the value of the scroll
     = ()
    # Bind intermediate windows
    (self.mid_frame)
    # Auto-hide and appear
    ()

    # Added to the bearer frame
    layout = QGridLayout(self)
    (, 0, 0)
    (layout)

    # Set the size of the bearer frame to be the same as the scrollarea
    (pos_x, 0, 20, ())

  def resizeEvent(self, e):
    # resize changes the height of the scroll's s to make it the same as itself
    (0, 0, 20, ())


# Intermediate windows that accept scroll events
class MidFrame(QFrame):
  def __init__(self, father):
    super().__init__(father)
     = father

  def moveEvent(self, e):
    # move event binds to the move of the actual scrolling window
    .parent_.move(.parent_.x(), ().y())


app = QApplication(argv)
main = Main()
app.exec_()

The effect of this example:

This is the whole content of this article, I hope it will help you to learn more.