How to add a scrollbar to a window widget in PyQt5?

To add a scrollbar to a window widget in PyQt5, you can use the QScrollArea class. Here is a simple example code demonstrating how to add a scrollbar to a window widget:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QScrollArea, QLabel

class ScrollBarDemo(QWidget):
    def __init__(self):


    def initUI(self):
        self.setWindowTitle('Scroll Bar Demo')
        self.setGeometry(100, 100, 400, 300)

        vbox = QVBoxLayout()

        # 创建一个QLabel并设置长文本
        label = QLabel('Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
                      'Vestibulum auctor sem non accumsan. In pretium, ligula at '
                      'eleifend fermentum, lorem ex pellentesque sapien, et vestibulum '
                      'nunc lorem at erat. Integer ultrices lacinia rhoncus.')
        # 创建一个QScrollArea并添加QLabel
        scroll_area = QScrollArea()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ScrollBarDemo()

In the example above, we created a QLabel and set a long text to it, then added the QLabel to a QScrollArea. Finally, we added the QScrollArea to the window widget. Running this code, you will see a window widget with a scrollbar that allows you to scroll through the text content.

Leave a Reply 0

Your email address will not be published. Required fields are marked *