Superqt - Distributing QCollapsible Containers
12/21/2023, ThuSpacing Display Issues
By itself, the QCollapsible element placed in a QVBoxLayout or QHBoxLayout will not offer an out-of-the-box solution for a refined display of distributing containers or the containers contents predictably.
Problems
- QCollapsible grows taller than the current's window size when expanding a container that has a lot of content.
- The QCollapsible containers become evenly distributed when the window is sized vertically. The vertical shifting of content is disorientating. This might make sense in a mobile type of application, but not well suited for a desktop application.
To remedy these problems, you need to place the QCollapsible containers in a QScrollArea to solve the first problem. Then the QVBoxLayout or QHBoxLayout layouts needs a call to the addStretch
method which acts as a buffer to fill in the empty space to prevent the container space redistribution.
import sys
from PyQt6.QtWidgets import (QWidget, QScrollArea, QVBoxLayout, QMainWindow, QApplication, QLabel, QPushButton)
from superqt import QCollapsible
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Create layout and widgets
self.scroll = QScrollArea()
self.widget = QWidget()
self.vbox = QVBoxLayout()
collapsible = QCollapsible("Advanced analysis", collapsedIcon="►")
collapsible2 = QCollapsible("Some other analysis", collapsedIcon="►")
# Add contents to the collapsible containers
collapsible.addWidget(QLabel("This is the inside of the collapsible frame"))
for i in range(10):
collapsible.addWidget(QPushButton(f"Content button {i + 1}"))
collapsible2.addWidget(QLabel("Another note"))
# Add collapsible containers to the layout
self.vbox.addWidget(collapsible)
self.vbox.addWidget(collapsible2)
# Prevent the collapsible containers from distributing space evenly
self.vbox.addStretch()
# Scrollarea settings
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.widget)
self.widget.setLayout(self.vbox)
self.setCentralWidget(self.scroll)
# Initially resize window for better visibility
self.setGeometry(600, 100, 500, 200)
self.show()
if __name__ == '__main__':
app = QApplication([])
mainWindow = MainWindow()
sys.exit(app.exec())
Improved display results