简体   繁体   中英

Changing a layout after it has been set on a widget PyQt5

I have a QStackedWidget object with three different QWidgets added to it. I initialize the the layouts for each of those and set them accordingly when the program starts up. However, as the user manipulates data from one, the data represented on another may change. I have already written working functions to change the layout when the state changes, but it never updates the layout from the one that was set when the QWidget.setLayout() call first happened.

class UI(self):
    def __init__(self):
        #create baseLayout
        #create emptyLayout
        self.layout = baseLayout

    def updateLayout(self):
        if empty:
            self.layout = emptyLayout
        else:
            self.layout = baseLayout

class MainWindow(self):
    def __init__(self, UI):
        self.centerWidget = QStackedWidget()
        self.childWidget = QWidget()
        self.childWidget.setLayout(UI.layout)
        self.centerWidget.addWidget(childWidget)

So in the above example if the updateLayout() function is called and changes the UI's layout to emptyLayout, it does not change how it appears when selecting the childWidget.

I suppose .setLayout isn't meant to update as the layout itself changes, but is there some other way to pull this off? I'm still only a few months into PyQt5 and not a master at it so if there is a better way to do this I'm all ears.

EDIT: I ran across the answer on this small blog site so I'm sharing it here. https://myprogrammingnotes.com/remove-layout.html

The short of it is that the copy constructor of QLayout is private and finding ways to save references to layouts is far beyond easy. He recommends setting layouts needed this way to be attached to their own widgets and then using .setVisible() to "turn them on or off."

Doing this could get out of hand fast and become hard to follow, but for my case it's fine and works well without the need for multiple new methods since I only need it in two places.

Your question is very similar to this

To remove in a layout

item=self.layout.takeAt(#widgetitem index to take out)
self.layout.removeItem(item)

To add in a layout

self.layout.addItem(QLabel("new item"))

To add layout in a layout

self.layout.addLayout(baseLayout) # to add into a layout (make sure if its horizontally layout or vertical layout because it will be added accordingly 

to remove layout refer to this Question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM