alphanumeric
alphanumeric

Reputation: 19329

Python: How to unassign Layout from GroupBox in PyQt

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?

Upvotes: 2

Views: 2006

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

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)

Upvotes: 3

Related Questions