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.
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.
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.
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.
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_())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With