将布局从父窗口添加到另一个布局中

问题描述 投票:1回答:1

我是这个领域的新手,希望这不是一个愚蠢的问题我在Mac上使用Python 3.8的PyQt5如果可能,我想从父窗口向另一个布局添加一个layout(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()
python pyqt pyqt5 qlayout
1个回答
1
投票

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

如果要通过另一个布局将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)
© www.soinside.com 2019 - 2024. All rights reserved.