Python: How to unassign Layout from GroupBox in PyQt

Question:

A groupbox:

myGroupBox = QtGui.QGroupBox()

and two layouts:

layoutA = QtGui.QVBoxLayout()
layoutB = QtGui.QVBoxLayout()

I assign layoutA to myGroupBox:

myGroupBox.setLayout(layoutA)

Later there is a need to re-assign layoutB to myGroupBox:

myGroupBox.setLayout(layoutB)

But getting a warning…

QWidget::setLayout: Attempting to set QLayout "" on QWidget "", which already has a layout

Is it possible to avoid this warning? How to remove a layout from myGroupBox before attempting to assign another?

Asked By: alphanumeric

||

Answers:

In order to set a new, top-level layout for a widget, you must delete the existing one and all its child items. Deleting the child items is fairly straightforward, but deleting the layout itself must done forcibly using the sip module.

Here’s an implementation:

from PyQt5 import sip

def deleteLayout(layout):
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                deleteLayout(item.layout())
        sip.delete(layout)

If you want to keep the existing layout and all its child items, give the widget a permanent top-level layout, and then just switch sub-layouts, like this:

    self.widget = QtWidgets.QWidget(self)
    layout = QtWidgets.QVBoxLayout(self.widget)
    layout.setContentsMargins(0, 0, 0, 0)
    self.vbox1 = QtWidgets.QVBoxLayout()
    self.vbox2 = QtWidgets.QVBoxLayout()
    layout.addLayout(vbox1)
    ...

    self.widget.layout().removeItem(self.vbox1)
    self.widget.layout().addLayout(self.vbox2)
Answered By: ekhumoro
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.