从父窗口向另一个布局添加布局

4
我是新手,希望我的问题不会显得很愚蠢。 我正在使用Python 3.8上的PyQt5,并且在mac上工作。 如果可能的话,我想从父窗口向另一个布局添加布局(addLayout)!
这是一个例子:我有一个类(ParentWindow),它有许多小部件和水平箱布局。 (ChildWindow)是从ParentWindow继承的类,它也有小部件和其他布局;问题是:我可以在子窗口中添加布局吗? 如果我在ChildWindow中使用setLayout,它会忽略它并显示消息: (QWidget :: setLayout:尝试在ChildWindow“”上设置QLayout“”,该窗口已经有布局)。那么,我可以在父窗口布局中使用addLayout吗?如何实现?
# The Parent Class
from PyQt5.QtWidgets import  QWidget, QHBoxLayout,QLabel
class ParentWindow(QWidget):
    def __init__(self):
        super().__init__()
        title = "Main Window"
        self.setWindowTitle(title)
        left = 000; top = 500; width = 600; hight = 300
        self.setGeometry(left, top, width, hight)
        MainLayoutHbox = QHBoxLayout()
        header1 = QLabel("Header 1")
        header2 = QLabel("Header 2")
        header3 = QLabel("Header 3")
        MainLayoutHbox.addWidget(header1)
        MainLayoutHbox.addWidget(header2)
        MainLayoutHbox.addWidget(header3)
        self.setLayout(MainLayoutHbox)
# End of Parent Class


# The SubClass

from PyQt5.QtWidgets import QApplication,   QVBoxLayout, QHBoxLayout,  QTabWidget, QLabel
import sys

from ParentWindow import ParentWindow


class ChildWindow(ParentWindow):
    def __init__(self):
        super().__init__()
        vbox = QVBoxLayout()
        MainLabel= QLabel("My Window")

        vbox.addWidget(MainLabel)

        self.setLayout(vbox) # This show the Warning  Error

        # I assume the below code should work to extend the parent layout!! But it gives error
        # parent.MainLayoutHbox.addLayout(vbox)




if __name__ == "__main__":
    App = QApplication(sys.argv)
    MyWindow= ChildWindow()
    MyWindow.show()
    App.exec()
1个回答

4

ChildWindow 是 ParentWindow,也就是说,ChildWindow 具有在 ParentWindow 中预设的属性。当你添加布局并使用代码“加入”布局时,Qt 会提示你:QWidget::setLayout: Attempting to set QLayout "" on ChildWindow "", which already has a layout,这表明你已经有了布局(即从父类继承下来的布局)。

如果你想通过另一个布局将 MainLabel 添加到已有布局中,则必须使用“layout()”方法访问继承的布局并将其添加进去:

class ChildWindow(ParentWindow):
    def __init__(self):
        super().__init__()
        vbox = QVBoxLayout()
        MainLabel= QLabel("My Window")
        vbox.addWidget(MainLabel)
        # self.layout() is MainLayoutHbox
        self.layout().addLayout(vbox)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接