Pyqt: Getting Widgets to Resize Automatically in a Qdialog

PyQt: getting widgets to resize automatically in a QDialog

QMainWindow has special behavior for the central widget that a QDialog does not. To achieve the desired behavior you need to create a layout, add the text area to the layout and assign the layout to the dialog.

PyQt Automatically resize widget in scroll area

You should not add the widgets directly to scroll_layout but create another layout, and in that layout add the widgets and use addStretch() so that it does not occupy the height of the first layout but the necessary one.

def populate(self):
self.widgets = []
self.scroll_widget = QtWidgets.QWidget()
self.scroll_widget.setAutoFillBackground(True)
self.scroll_widget.setStyleSheet("background-color:red;")
self.scroll_layout = QtWidgets.QVBoxLayout()
self.scroll_widget.setLayout(self.scroll_layout)

lay = QtWidgets.QVBoxLayout() # <---
self.scroll_layout.addLayout(lay) # <---
self.scroll_layout.addStretch() # <---

for i in range(1, 11):
widget = smallWidget(str(i))
self.widgets.append(widget)
lay.addWidget(widget) # <---

self.scroll_area.setWidget(self.scroll_widget)

Update:

If you want the size of scroll_widget to be adjusted you must call adjustSize() an instant later with a QTimer since the geometry changes are not applied instantly

def filter(self, text):
for widget in self.widgets:
widget.setVisible(text in widget.name)
QtCore.QTimer.singleShot(0, self.scroll_widget.adjustSize)

Resize QDialog at a runtime

If you don't need manual resize, you can add

layout()->setSizeConstraint(QLayout::SetFixedSize);

to the dialog constructor, then the layout takes over the responsibility to automatically resize when widgets are shown or hidden.

PyQt: Prevent Resize and Maximize in QDialog?

Use setFixedSize:

mydialog.setFixedSize(width, height)

Automatically resizing a window based on its contents

You can resize the window to minimumSizeHint() after the number of widgets is changed :

resize(minimumSizeHint());

This will shrink the window to minimum size. But you should consider that the minimum size is not computed until some events are processed in the event loop. So after some widgets are hidden and some other are shown, just process the event loop for some iterations and then resize to minimum.

It's like :

for(int i=0;i<10;i++)
qApp->processEvents();

resize(minimumSizeHint());

A better solution is to single shot a QTimer which calls a slot in which you resize the window to minimum. This way when you resize the window, the minimum size hint is computed correctly.

QDialog paints widgets black when adding new ones

Thanks for the help guys, but it turned out to be an errant stylesheet.



Related Topics



Leave a reply



Submit