I am new to this field, and I Hope this not seems a stupid question I am using PyQt5 for Python 3.8 on mac I want to add a layout(addLayout) to another layout from the parent window if it is possible!
This is an example: I have a Class (ParentWindow) it has many widgets and hboxlayout. (ChildWindow) is a class inherited from ParentWindow and it has also widgets and other layout; the question: can I add layout in the child window? If I use setLayout in the ChildWindow it ignores it and show the message: (QWidget::setLayout: Attempting to set QLayout "" on ChildWindow "", which already has a layout) So, can I use addLayout to the parent window layout? And how
# 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()
ChildWindow is a ParentWindow, that is, ChildWindow has the preset properties in ParentWindow that where you added a layout and with your Z code you are adding a layout but Qt tells you: QWidget::setLayout: Attempting to set QLayout "" on ChildWindow "", which already has a layout which indicates that you already have a layout (the layout that you inherited from the parent ).
If you want to add MainLabel to the pre-existing layout through another layout then you must access the inherited layout using the "layout()" method and add it:
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)