您的位置:宽带测速网 > 编程知识 > PyQt5中怎么创建一个可滚动的窗口

PyQt5中怎么创建一个可滚动的窗口

2025-06-17 15:28来源:互联网 [ ]

要在PyQt5中创建一个可滚动的窗口,你可以使用QScrollArea类。以下是一个简单的示例代码:

import sysfrom PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout, QLabel, QScrollAreaclass ScrollableWindow(QWidget):def __init__(self):super().__init__()layout = QVBoxLayout()scroll = QScrollArea()for i in range(50):label = QLabel(f"Label {i}")layout.addWidget(label)widget = QWidget()widget.setLayout(layout)scroll.setWidget(widget)scroll.setWidgetResizable(True)main_layout = QVBoxLayout()main_layout.addWidget(scroll)self.setLayout(main_layout)self.setWindowTitle("Scrollable Window")if __name__ == '__main__':app = QApplication(sys.argv)window = ScrollableWindow()window.show()sys.exit(app.exec_())

在这个示例中,我们创建了一个QWidget窗口,并在窗口中使用了QScrollArea。我们在QScrollArea中添加了50个标签,并在滚动时可以看到所有的标签。