What is the best way to resize the main window automatically if one widget is hidden? I also need to resize the window if I make the widget visible again. See the images below...
What settings should I set in Qt Designer for MainWindow (sizePolicy), centralwidget (sizePolicy, layoutSizeConstraint) and gridLayout (sizePolicy, layoutSizeConstraint) in particular?
How can I hide the textEdit widget? self.textEditObject.setVisible(False)
works: textEditObject is not visible, but is this the right way to resize the window?
I think I don't understand some basic stuff, as I cannot get the desired behaviour.
Even simpler than a manual resize is QWidget.adjustSize().
Here is an example:
from PySide import QtGui
def hide_show():
x.setVisible(not x.isVisible()) # toggles visibility of the label
w.adjustSize() # adjusts size of widget
app = QtGui.QApplication([])
w = QtGui.QWidget()
l = QtGui.QVBoxLayout(w)
b = QtGui.QPushButton('Click me')
l.addWidget(b)
x = QtGui.QLabel('Some Text')
l.addWidget(x)
b.clicked.connect(hide_show)
w.show()
app.exec_()
If you have a QMainWidget
I actually only managed to shrink it somewhat but not completely. Maybe than other solutions are better.
from PySide import QtGui
def hide_show():
x.setVisible(not x.isVisible()) # toggles visibility of the label
w2.adjustSize() # adjusts size of widget
w.adjustSize() # adjusts size of main window
app = QtGui.QApplication([])
w = QtGui.QMainWindow()
w2 = QtGui.QWidget()
l = QtGui.QVBoxLayout(w2)
b = QtGui.QPushButton('Click me')
l.addWidget(b)
x = QtGui.QTextEdit('Some Text')
l.addWidget(x)
b.clicked.connect(hide_show)
w.setCentralWidget(w2)
w.show()
app.exec_()
You can resize the window to minimumSizeHint()
after hiding the widget:
self.resize(minimumSizeHint())
This will shrink the window to minimum size.
If you want to only shrink in height, then you can do something like:
self.resize(width(), minimumSizeHint().height())
But you should consider that the minimum size is not computed until some events are processed in the event loop. So when you hide your widget, just process the event loop for some iterations and then resize to minimum.
It's like :
for i in range(0, 10):
QApplication.processEvents()
self.resize(width(), minimumSizeHint().height())
Another option 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With