Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySide: What is the best way to resize the main window if one widget is hidden?

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.

enter image description here

like image 341
Igor Avatar asked Jan 28 '15 21:01

Igor


2 Answers

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_()
like image 189
Trilarion Avatar answered Nov 02 '22 21:11

Trilarion


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.

like image 45
Nejat Avatar answered Nov 02 '22 22:11

Nejat