Home > database >  PQYT Make QGridLayout scrollable
PQYT Make QGridLayout scrollable

Time:06-08

I was wondering if it is possible to add a QScrollArea to a QGridLayout? Below is my attempt however, it always fails with the error.

TypeError: setWidget(self, QWidget): argument 1 has unexpected type 'QGridLayout'

Is this method only possible for combo and list boxes? I am basically passing QPixmap images into a QGridLayout which needs to be scrolled. Any help much appreciated thank you.

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class PicClip(QWidget):

    def __init__(self):
        super().__init__()
        # Load image
        self.im = QPixmap("1.jpg")
        self.im1 = QPixmap("1.jpg")
        # Label 1
        self.label = QLabel()
        self.label.setPixmap(self.im)
        # Label 2
        self.label1 = QLabel()
        self.label1.setPixmap(self.im1)
        # Make Grid
        self.grid = QGridLayout()
        # Create widgets to grid
        self.grid.addWidget(self.label, 0, 1, alignment=Qt.AlignCenter)
        self.grid.addWidget(self.label1, 1, 1, alignment=Qt.AlignCenter)
        # Set layout of Grid
        self.setLayout(self.grid)
        # Scroll 
        scroll = QScrollArea()
        scroll.setWidget(self.grid)
        scroll.setWidgetResizable(True)
        # Show 
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PicClip()
    sys.exit(app.exec_())

CodePudding user response:

self.grid is layout and you are trying to add layout using setWidget function. setWidget function only gets QWidget

simple trick is to add wrapper QWidget and set self.grid as its layout

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class PicClip(QMainWindow): # I modified this line to show window properly

    def __init__(self):
        super().__init__()
        # Load image
        self.im = QPixmap("1.jpg")
        self.im1 = QPixmap("1.jpg")
        # Label 1
        self.label = QLabel()
        self.label.setPixmap(self.im)
        # Label 2
        self.label1 = QLabel()
        self.label1.setPixmap(self.im1)
        # Make Grid
        self.grid = QGridLayout()
        # Create widgets to grid
        self.grid.addWidget(self.label, 0, 1, alignment=Qt.AlignCenter)
        self.grid.addWidget(self.label1, 1, 1, alignment=Qt.AlignCenter)
        # Set layout of Grid
        self.setLayout(self.grid)
        # Scroll
        scroll = QScrollArea()
        # add wrapper widget and set its layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(self.grid)
        scroll.setWidget(wrapper_widget)
        scroll.setWidgetResizable(True)
        # Show
        self.setCentralWidget(scroll)  # I modified this line to show window properly
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PicClip()
    sys.exit(app.exec_())
  • Related