Search code examples
pythonpyqtpyqt5qlayout

Modifying layout in resize event


PyQt 5.9.2, Python 3.6.6, Windows 10

I want to hide/show widgets dynamically depending on current width of their container widget. If space takes less than 10% of the whole width button "One" is hidden, then button "Two". When a user makes container larger the buttons are shown again: "Two", then "One".

enter image description here

Here's a very basic version of my implementation which mostly works, but there's one big problem. I start resizing, button "One" hides, but then some constraint comes into place and the container cannot be reduced in size anymore. I have to release mouse button and start the process again to hide button "Two" too.

enter image description here

import sys
from PyQt5 import QtWidgets

form, space, widgets = None, None, None

def resize_event(event):
    if free_space_width() < 0:
        visible_w = [w for w in widgets if w.isVisible()]
        if len(visible_w) > 1:  # do not hide the last one
            for w in visible_w:
                w.hide()
                if free_space_width(w.width()) >= 0:
                    break  # enough space
    else:
        invisible_w = [w for w in widgets if not w.isVisible()]
        for w in reversed(invisible_w):
            if free_space_width(-w.width()) < 0:
                break
            w.show()


def free_space_width(shift=0):
    "Free space should be at least 10% of the bar width"
    return space.width() + shift - 0.1 * form.width()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    form = QtWidgets.QWidget()
    layout = QtWidgets.QHBoxLayout(form)
    layout.setSpacing(0)  # for simplicity
    form.resize(480, 64)
    form.resizeEvent = resize_event

    widgets = [QtWidgets.QPushButton("test button %d" % (i + 1), form)
               for i in range(3)]
    for i in widgets:
        layout.addWidget(i)
    space = QtWidgets.QWidget(form)  # stretchable space
    s_policy = space.sizePolicy()
    s_policy.setHorizontalStretch(1)
    space.setSizePolicy(s_policy)
    layout.addWidget(space)

    form.show()
    sys.exit(app.exec_())

Solution

  • then some constraint comes into place and the container cannot be reduced in size

    layout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint)

    I think you should implement it under this code like this.

    layout = QtWidgets.QHBoxLayout(form)
    layout.setSpacing(0)  # for simplicity
    layout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint)