Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt5 - How to display image in QMainWindow class?

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.

like image 278
TheCrystalShip Avatar asked Jul 19 '18 19:07

TheCrystalShip


People also ask

How do I display images in PyQT?

A QPixmap can be used to show an image in a PyQT window. QPixmap() can load an image, as parameter it has the filename. To show the image, add the QPixmap to a QLabel. QPixmap supports all the major image formats: BMP,GIF,JPG,JPEG,PNG,PBM,PGM,PPM,XBM and XPM.

How do I insert an image into PyQT?

From the property editor dropdown select "Choose File…" and select an image file to insert. As you can see, the image is inserted, but the image is kept at its original size, cropped to the boundaries of the QLabel box. You need to resize the QLabel to be able to see the entire image.

How do I display an image in QWidget in Python?

To load an image from a file, you can use the QPixmap. load() method. This will return a True or False value depending on whether the image was successfully loaded. Once you have loaded an image into a QPixmap, you can then display it by creating a QLabel and setting the pixmap property of the label to the QPixmap.


1 Answers

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

like image 106
S. Nick Avatar answered Sep 28 '22 07:09

S. Nick