QWidget::setLayout: Attempting to set QLayout "" on Window "", which already has a layout

Heads up! You've already completed this tutorial.

I am a Beginner. I do not understand this error message. Who can explain it to me. :-)

Attempting to set QLayout "" on Window "", which already has a layout

python
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QApplication, QWidget, QMainWindow,
    QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout, QStackedLayout,
    QPushButton, QComboBox, QLineEdit, QCheckBox, QRadioButton,
)
class Window(QWidget):
    def __init__(self):
        super().__init__()

        layVer = QVBoxLayout()
        self.comBox = QComboBox()
        self.comBox.addItems(["One", "Two", "Three"])
        self.comBox.activated.connect(lambda x: self.onComBox(x))
        layVer.addWidget(self.comBox)
        self.setLayout(layVer)

        layHor = QHBoxLayout()
        self.cheBox1 = QCheckBox("A")
        layHor.addWidget(self.cheBox1)
        self.setLayout(layHor)

        layVer.addLayout(layHor)

    def onCheBox(self, s):
        print(s)

    def onComBox(self, s):
        print(s, self.comBox.currentText())

if __name__ == "__main__":
    app = QApplication([])
    win = Window()
    win.show()
    app.exec_()

PedanticHacker

Firstly, delete the line self.setLayout(layVer)

then fix

python
self.setLayout(layHor)

layVer.addLayout(layHor)

to be

python
layVer.addLayout(layHor)

self.setLayout(layVer)

Martin Fitzpatrick

This error occurs because you're trying to set a layout on a QMainWindow. The QMainWindow is a special widget which has a built-in layout, to handle things link menus, toolbars and dock widgets.

For windows based on QMainWindow you can only set a central widget -- that is, the widget that appears in the center of the window. But if you remember from the PyQt5 layouts tutorial you can set a layout on an empty QWidget and add anything you want to it that way.

So the trick is: for controlling the layout of a mainwindow we first create a QWidget to act as a "container", use that widget as our central widget and apply the layout to it to add other widgets.


_Ali Sanawi Garrousi__

Merci now it works!

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak