简体   繁体   中英

Add scrollbar to grid layout in pyqt4

I have coded the following python program. It shows multiple icons in a grid view.

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_())

I want to add a scrollbar to the window containing icons but don't know how.

You can use a QScrollArea . Put your GridLayout in a Widget and put that Widget in a ScrollArea .

Mind the Notes in the documentation:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM