PyQt5 - How to display image in QMainWindow class?

TheCrystalShip picture TheCrystalShip · Jul 19, 2018 · Viewed 18.1k times · Source

I'm trying to display a picture in a QMainWindow class:

from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap
import sys


class Menu(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Title")
        label = QLabel(self)
        pixmap = QPixmap('capture.png')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Menu()
    sys.exit(app.exec_())

But it doesn't show the image, just opens the window. I'm insisting on a QMainWindow class because I'm trying to write something like a paint app, so I'll be able to write a menu, and I'll be able to write on the picture.

Any suggestions would be appreciated.

Thanks.

Answer

S. Nick picture S. Nick · Jul 19, 2018

QMainWindow.setCentralWidget(widget)

Sets the given widget to be the main window’s central widget.

from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap
import sys


class Menu(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Title")
        
        self.central_widget = QWidget()               
        self.setCentralWidget(self.central_widget)    
        lay = QVBoxLayout(self.central_widget)
        
        label = QLabel(self)
        pixmap = QPixmap('logo.png')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        
        lay.addWidget(label)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Menu()
    sys.exit(app.exec_())

enter image description here