I have this sample of code:
import sys
from PyQt4.QtGui import (QApplication, QHBoxLayout, QVBoxLayout, QDialog,
QFrame, QPushButton, QComboBox)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
moreButton = QPushButton('moreButton')
moreButton.setCheckable(True)
resizeButton = QPushButton('Resize')
combo = QComboBox()
combo.addItems(['item1', 'item2'])
layout1 = QHBoxLayout()
layout1.addWidget(moreButton)
layout1.addWidget(resizeButton)
layout2 = QHBoxLayout()
layout2.addWidget(combo)
self.frame = QFrame()
self.frame.setLayout(layout2)
self.frame.hide()
layout3 = QVBoxLayout()
layout3.addLayout(layout1)
layout3.addWidget(self.frame)
moreButton.toggled.connect(self.frame.setVisible)
moreButton.clicked.connect(self.method)
resizeButton.clicked.connect(self.method)
self.setLayout(layout3)
self.resize(630, 50)
def method(self):
if self.frame.isVisible():
self.resize(630, 150)
else:
self.resize(630, 250)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
I run it and when moreButton clicked the ComboBox appears or disappears. Dialog’s size also changes. But if I change the method to:
def method(self):
if self.frame.isVisible():
self.resize(630, 150)
else:
self.resize(630, 50)
(in order to set the initial size when combo is hidden) the resizing does not work. However, if I click resizeButton -which is connected to the same method- the resizing works properly.
I know that there are other ways to achieve such a result (eg. layout.setSizeConstraint(QLayout.SetFixedSize)), but I want to declare size explicitly.
What am I doing wrong?
My guess is that you are trying to resize the
QDialogbefore it has time to re-adjust its size after you hide stuff. So at the timeresizeis called it has aminimumSizethat makes sure the buttons and the combobox visible. When you call it after some time, it now has propermiminumSizeand responds properly.A quick fix is manually overriding
minimumSizebefore resizing:But, if I were to tackle this, I’d just leave managing resizing to the layout and use
sizeConstraint. That’s what these layouts for anyways.