The QPixmap class is used to display the image inside a PyQt/Pyside window, either as a QPainterDevice object or loaded into a control, usually a label or button.
QPixmap can read image file types such as BMP, GIF, JPG, etc. If you want to display animated GIFs, you can use QMovie. PyQt can also display videos.
QPixmap is one of the widgets used to process images. It is optimized for displaying images on the screen. In our code example, we will use QPixmap to display the image on the window.
If you are new to PyQt, I suggest this course/book.
PyQt show image
The code below loads an image using a QPixmap. It attaches the QPixmap to a QLabel. The label is added to an QHBoxLayout and the QHboxLayout to the window.
from PyQt5.Qt import (QWidget, QHBoxLayout, QLabel, QApplication)
from PyQt5.QtGui import QPixmap
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
pixmap = QPixmap("cat.jpg")
lbl = QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Image with PyQt')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
In our example, we display the image on the window.
pixmap = QPixmap("cat.png")
We create a QPixmap object. It takes the name of the file as an argument.
lbl = QLabel(self)
lbl.setPixmap(pixmap)
We put the pixmap into the QLabel widget.
Alternatively you can use designer.
PySide2 show image
The PySide2 version is similar. Both the PyQt and PySide toolkits are actively maintained, and by now more or less equal in features and quality. There are only few, rather unimportant differences.
import sys
from PySide2.QtGui import QPixmap
from PySide2.QtWidgets import QMainWindow, QApplication, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.title = "Load image in PySide2"
self.setWindowTitle(self.title)
label = QLabel(self)
pixmap = QPixmap('cat.jpg')
label.setPixmap(pixmap)
self.setCentralWidget(label)
self.resize(pixmap.width(), pixmap.height())
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Reference
Top comments (0)