pyqt4 already has a layout. How to 'detect' it or change?

Question:

I’m trying to set a layout manager. But getting the message:

QLayout: Attempting to add QLayout "" to Window "", which already has a layout

How can I change or detect which type the layout is? I’d like to use the boxlayout as it seems to be prefered.

import sys
from PyQt4 import QtGui as qt

class Window(qt.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        #Lav widgets
        self.CreateWidgets()       

    def CreateWidgets(self):
        btn = qt.QPushButton("Fetch", self)
        btn.clicked.connect(self.GetData)

        self.layout = qt.QVBoxLayout(self)

        self.setGeometry(560, 240, 800, 600)
        self.setWindowTitle("We do not sow")
        self.show()

    def GetData(self):
        print("Hello World!")

app = qt.QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())
Asked By: vandelay

||

Answers:

The QMainWindow class has built-in support for toolbars and dock-widgets, and a menubar and statusbar – so it has to have a fixed layout. Therefore, rather than adding child widgets to the main window itself, you must set its central widget, and then add the child widgets to that:

    def CreateWidgets(self):
        btn = qt.QPushButton("Fetch", self)
        btn.clicked.connect(self.GetData)

        widget = qt.QWidget(self)
        layout = qt.QVBoxLayout(widget)
        layout.addWidget(btn)

        self.setCentralWidget(widget)

        self.setGeometry(560, 240, 800, 600)
        self.setWindowTitle("We do not sow")
Answered By: ekhumoro
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.