将滚动条添加到pyqt4中的网格布局

Add scrollbar to grid layout in pyqt4

我编写了以下 python 程序。它在网格视图中显示多个图标。

import sys
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore 

class Main(QtGui.QMainWindow):
        def __init__(self, parent = None):
            super(Main, self).__init__(parent)

            self.centralWidget=QWidget()
            scrollArea=QScrollArea()
            scrollArea.setWidgetResizable(True)
            scrollArea.setWidget(self.centralWidget)
            self.setCentralWidget(self.centralWidget)
            w=QGridLayout()

            size=128
            icon=QIcon()
            mode=QIcon.Normal
            state=QIcon.Off
            pixma = QPixmap('a.png') 
            icon.addPixmap(pixma,mode,state)
            positions = [(i,j) for i in range(5) for j in range(4)]
            for position in positions:
                label=QLabel()
                label.setPixmap(icon.pixmap(size,QIcon.Normal,state))
                w.addWidget(label,*position) 

            self.centralWidget.setLayout(w)


a = QApplication(sys.argv) 
q=Main() 
q.show() 
sys.exit(a.exec_())

我想向包含图标的 window 添加滚动条,但不知道如何。

您可以使用 QScrollArea。 将你的 GridLayout 放入 Widget 并将 Widget 放入 ScrollArea.

注意文档中的注意事项:

When using a scroll area to display the contents of a custom widget, it is important to ensure that the size hint of the child widget is set to a suitable value. If a standard QWidget is used for the child widget, it may be necessary to call QWidget::setMinimumSize() to ensure that the contents of the widget are shown correctly within the scroll area.