简体   繁体   中英

Widgets not showing up in maximized PyQt5 Window

Here's my code:

import sys
from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
    super().__init__()

    self.showMaximized()
    self.setWindowTitle("MyCoolBrowser")
    self.label = QtWidgets.QPushButton("Click me", self)
    self.label.setGeometry(0, 0, 50, 50)

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

My pushbutton is not shown in the window when I run my code. But, When I delete the line "self.showMaximized()", then the pushbutton is shown. Can anyone please help?

Widgets created just as children (without being added to a layout) are not automatically shown after their parent has already been shown.

The simple solution is to move showMaximized() after the button is created, as it's always good practice to call any show() related function after all objects are created.

The good answer is to correctly set a central widget (which is what a QMainWindow shows as its main content) and possibly use layout managers if more widgets are going to be shown, and avoid any attempt to use fixed geometries (size and position) which is considered a bad practice (use spacers or stretchs if needed):

import sys
from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("MyCoolBrowser")
        container = QtWidgets.QWidget()
        self.setCentralWidget(container)

        layout = QtWidgets.QVBoxLayout(container)

        self.label = QtWidgets.QPushButton("Click me")
        layout.addWidget(self.label)

        self.editor = QtWidgets.QLineEdit()
        layout.addWidget(self.editor)

        # add a "stretch" at the bottom of the layout in order to 
        # "push" everything on top
        layout.addStretch()

        self.showMaximized()

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM