Unset from QWidget to pyside

I have a problem installing a new layout in my QWidget object. I am starting to set one type of layout when the application is exec, and I want to change it when the button is clicked with a new layout. In the PySide documentation, I read the following:

Installs the layout manager of this widget in the layout.

If the layout manager is already installed on this widget, PySide.QtGui.QWidget will not 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 a new location.

But how can I delete an existing layout manager? What are the methods I should apply on my QWidget?

+4
source share
1 answer

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

In your specific example, you will need a method to recursively remove and remove all objects from the layout (i.e. all its child widgets, separators, and other layouts). As well as a method for building and adding a new layout.

Here is 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_())
+3
source

Source: https://habr.com/ru/post/1527768/


All Articles