Why is PyQt5 not displaying button? [duplicate]

When the menu class is inheriting from QWidgets class, the button is displayed, however, when is inheriting from QMainWindow the same button doesnt display. I’ve searched everywhere but couldn’t find a explanation.

from PyQt5.QtWidgets import QMainWindow, QFormLayout, QPushButton, QApplication, QWidget
import sys


class Menu(QMainWindow):
    """
    Create menu object
    """

    def __init__(self, parent=None):
        """
        Initialize main menu
        """
        super().__init__(parent)
        self.file = None
        self.fields_create()
        self.create_table()

    def fields_create(self):
        """
        Create buttons and LineEdits
        """
        # Settings Button
        self.settings_btn = QPushButton()
        self.settings_btn.setText("Settings")
        self.settings_btn.clicked.connect(self.settings_click)

    def create_table(self):
        """
        create and display table
        """
        self.flo = QFormLayout()
        self.flo.addRow(self.settings_btn)
        self.setLayout(self.flo)

    def settings_click(self):
        print("clicked")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Menu()
    win.show()
    sys.exit(app.exec_())

  • QMainWindow has its own internal layout, which cannot be accessed to add other widgets. A central widget must be set instead, as explained in the documentation. Create a container QWidget, set the layout on it, and then call setCentralWidget() with that widget.

    – 

try to replace :

self.settings_btn = QPushButton()

with

self.settings_btn = QPushButton(self)

Leave a Comment