user3329477
user3329477

Reputation: 41

Unset layout from QWidget in pyside

I have a problem to set a new layout in my QWidget object. I start to set one type of layout when the app exec, and I want to change it when the button is pressed with a new layout. In the documentation of PySide I read this:

Sets the layout manager for this widget to layout.

If there already is a layout manager installed on this widget, PySide.QtGui.QWidget won’t let you install another. You must first delete the existing layout manager (returned by PySide.QtGui.QWidget.layout() ) before you can call PySide.QtGui.QWidget.setLayout() with the new layout.

But how can I delete the existing layout manager? What are the methods which I must apply on my QWidget object?

Upvotes: 4

Views: 3227

Answers (1)

ekhumoro
ekhumoro

Reputation: 120768

If you're new to PySide/PyQt, see the Layout Management article in the documentation for an overview of Qt's layout system.

For your specific example, you will need a method to recursively remove and delete all the objects from a layout (i.e. all its child widgets, spacer-items and other layouts). And also a method to build and add the new layout.

Here's a simple demo:

from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.changeLayout(QtCore.Qt.Vertical)
        self.button = QtGui.QPushButton('Horizontal', self)
        self.button.clicked.connect(self.handleButton)
        layout.addStretch()
        layout.addWidget(self.button)

    def handleButton(self):
        if self.button.text() == 'Horizontal':
            self.changeLayout(QtCore.Qt.Horizontal)
            self.button.setText('Vertical')
        else:
            self.changeLayout(QtCore.Qt.Vertical)
            self.button.setText('Horizontal')

    def changeLayout(self, direction):
        if self.layout().count():
            layout = self.layout().takeAt(0)
            self.clearLayout(layout)
            layout.deleteLater()
        if direction == QtCore.Qt.Vertical:
            layout = QtGui.QVBoxLayout()
        else:
            layout = QtGui.QHBoxLayout()
        for index in range(3):
            layout.addWidget(QtGui.QLineEdit(self))
        self.layout().insertLayout(0, layout)

    def clearLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.clearLayout(item.layout())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 100)
    window.show()
    sys.exit(app.exec_())

Upvotes: 3

Related Questions