Search code examples
pythonqtpyqtpyqt5pyside

Clearing Grid Layout in scroll area


I have a grid layout that's inside a scroll area. I want to have 5 columns and 200 rows maximum at a time. When a grid item is clicked I want to remove all items in the grid and add new ones.

However, when I start with around 50 items(10x5) and add 1000(200x5) items after clearing the first 50 nothing shows up on the screen. I assume it is because they are too small.

If I do 750(150x5) they show up very small.

The issue is that if I start with 1000 items everything looks how they should be.

Below is my reproducible example to my problem.

import sys

from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

class GridButton(QPushButton):
    def __init__(self, parent, tab, grid) -> None:
        super().__init__(parent)
        self.tab = tab
        self.grid = grid
        self.grid_wid = parent

    def onclick(self):
        self.tab.clear()
        for i in range(150):
            for j in range(5):
                btn = GridButton(self.grid_wid, self.tab, self.grid)
                btn.setText(f"nButton: {i}")
                btn.clicked.connect(btn.onclick)
                self.grid.addWidget(btn, i, j)

class Test(QWidget):
    def __init__(self, parent) -> None:
        super().__init__(parent)

        self.sc = QScrollArea(self)
        self.sc.setGeometry(0, 0, 1024, 600)
        self.grid_wid = QWidget()
        self.grid = QGridLayout(self.grid_wid)
        
        for i in range(10):
            for j in range(5):
                btn = GridButton(self.grid_wid, self, self.grid)
                btn.setText(f"Button: {i}")
                btn.clicked.connect(btn.onclick)
                self.grid.addWidget(btn, i, j)

        self.sc.setWidget(self.grid_wid)

    def clear(self):
        for i in reversed(range(self.grid.count())):
            widgetToRemove = self.grid.itemAt(i).widget()
            widgetToRemove.setParent(None)
            widgetToRemove.deleteLater()



class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.tabs = Test(self)
        self.setWindowTitle("GUI")

        self.setFixedSize(QSize(1024, 600))

        self.setCentralWidget(self.tabs)
        self.show()


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

50 items

After clicking for 1000


Solution

  • From @CarlHR's answer:

    self.sc.setWidgetResizable(True)