在小部件PyQt5上设置布局后更改布局

2024-10-03 00:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个QStackedWidget对象,其中添加了三个不同的QWidget。我初始化了每个布局,并在程序启动时相应地设置它们。然而,当用户操作其中一个的数据时,在另一个上表示的数据可能会改变。我已经编写了工作函数来在状态更改时更改布局,但它从未更新QWidget.setLayout()调用首次发生时设置的布局

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)

因此,在上面的示例中,如果调用updateLayout()函数并将UI的布局更改为emptyLayout,则它不会更改选择childWidget时的显示方式

我想.setLayout并不意味着随着布局本身的变化而更新,但是有没有其他方法可以实现这一点呢?我对PyQt5的了解还只是几个月,还不是它的高手,所以如果有更好的方法,我会洗耳恭听

编辑:我在这个小博客上找到了答案,所以我在这里分享https://myprogrammingnotes.com/remove-layout.html

其缺点是QLayout的复制构造函数是私有的,找到保存对布局的引用的方法远远不容易。他建议将这种方式所需的布局设置为附加到自己的小部件上,然后使用.setVisible()来“打开或关闭它们”

这样做可能会很快失去控制,很难遵循,但对于我来说,这很好,而且不需要多种新方法,因为我只需要在两个地方使用它


Tags: 数据方法函数selfuidef布局class
1条回答
网友
1楼 · 发布于 2024-10-03 00:23:32

你的问题很像this

在布局中删除

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

添加布局

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

在布局中添加布局的步骤

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

删除布局的步骤 请参阅此Question

相关问题 更多 >