从父窗口向其他布局添加布局

时间:2020-04-21 09:52:13

标签: python pyqt pyqt5 qlayout

我是这个领域的新手,我希望这不是一个愚蠢的问题 我在Mac上使用PyQt5 for Python 3.8 如果可能的话,我想从父窗口向另一个布局添加一个布局(addLayout)!

这是一个示例:我有一个类(ParentWindow),它具有许多小部件和hboxlayout。 (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 个答案:

答案 0 :(得分:1)

ChildWindow是ParentWindow,即ChildWindow在ParentWindow中具有预设属性,您在其中添加了布局,并使用Z代码添加了布局,但是Qt告诉您: QWidget :: setLayout:尝试设置在子窗口“”上的QLayout“”已具有布局,表示您已经具有布局(从父级继承的布局)。

如果要通过另一个布局将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)