I have a QWidget with a QGridLayout populated by an array of QLineEdit widgets. Sometimes, upon building this QWidget, the QLineEdit widgets get squished as shown in the attached figure. Is there a way I can get the widget to expand to the correct size, so that the QLineEdits are tightly packed but not squished?
A minimum working example
import sys
from PySide2.QtWidgets import (
QScrollArea, QPushButton, QLineEdit, QWidget, QMainWindow, QApplication,
QVBoxLayout, QGridLayout)
class FaultyWidget(QScrollArea):
def __init__(self):
super(FaultyWidget, self).__init__()
self.push_button = QPushButton("Push")
self.push_button.clicked.connect(self._loadTextFields)
self.test_widget = QWidget()
self.test_widget.setLayout(QGridLayout())
for i in range(3):
self.test_widget.layout().addWidget(QLineEdit(), i, 0)
self.main_widget = QWidget()
self.main_widget.setLayout(QVBoxLayout())
self.main_widget.layout().addWidget(self.push_button)
self.main_widget.layout().addWidget(self.test_widget)
self.setWidget(self.main_widget)
def _loadTextFields(self):
self.test_widget.setParent(None)
self.test_widget = QWidget()
self.test_widget.setLayout(QGridLayout())
for i in range(6):
self.test_widget.layout().addWidget(QLineEdit(), i, 0)
self.main_widget.layout().insertWidget(1, self.test_widget)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setLayout(QVBoxLayout())
self.main_widget = FaultyWidget()
self.setCentralWidget(self.main_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())