Search code examples
qtlayoutpyqtpysideqframe

Subclassed QFrame not adjusting to it's layout


I'm trying to include a horizontal frame containing a label inside a vertical frame, but even though the label is displayed it's not in the right position and it's limited to a size of a standard QLabel

This is the main class:

class Launcher(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setFrame() #sets up window's geometry, works fine
        self.setContent() 
        self.show()

    def setContent(self):
        layout = QBoxLayout(QBoxLayout.TopToBottom)
        layout.addWidget(widgets.Logo(self), 0, Qt.AlignTop)
        self.setLayout(layout)

And this is the imported class from a "widgets" module

class Logo(QFrame):
    def __init__(self, parent):
        super().__init__(parent)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        text = QLabel("PyTitle", self)
        text.setAlignment(Qt.AlignCenter)
        text.setFont(QFont("impact", 48))
        layout.addWidget(text, 0, Qt.AlignCenter)
        self.setLayout(layout)
        self.show()

The result is this: enter image description here

If I forcefully resize both QLabel AND QFrame, it's visible, but still in the top-left.


Solution

  • You must not set a layout on a QMainWindow, because it already has one built in (to handle dock-widgets, the menu-bar, status-bar, etc).

    Instead, set a central-widget, and add all the widgets and layouts to that:

    class Launcher(QMainWindow):
        ...
        def setContent(self):
            widget = widgets.Logo(self)
            self.setCentralWidget(widget)
    

    (PS: you only need to call show() on the top-level window - for all other child widgets, it's redundant).