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
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
self.setLayout(layHor)
layVer.addLayout(layHor)
to be
layVer.addLayout(layHor)
self.setLayout(layVer)
Martin Fitzpatrick
Never miss an update
Enjoyed this? Subscribe to get new updates straight in your Inbox.
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!