This article covers the QPixmap widget in PyQt5.
PyQt5, with the QPixmap widget brings in support for displaying images in your GUI window. Using a QPixmap object and an appropriate display widget such as a Label, you can display and manipulate images on your PyQt5 GUI screen.
Using QPixmap in PyQt5
The code is pretty straightforward and simple. Be sure to import QPixmap from the right place, as its different from where you normally import widgets. (import from PyQt5.QtGui, not PyQt5.QtWidgets).
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel from PyQt5.QtGui import QIcon, QPixmap from PyQt5 import QtCore import sys app = QApplication(sys.argv) win = QMainWindow() win.setGeometry(400,400,500,450) win.setWindowTitle("CodersLegacy") label = QLabel(win) pixmap = QPixmap('Piechart.jpg') label.setPixmap(pixmap) label.adjustSize() win.show() sys.exit(app.exec_())
It’s important to call
label.adjustSize() else the full image will not show. The
adjustSize() function causes the label to increase in size in order to accommodate the image/text inside of it.
By using the
setPixmap() method on the label, the QPixmap object is assigned to that label. Our new label now holds an image, instead of text.
The image we loaded was a Pie chart produced by the Matplotlib library in Python.
A small list of useful methods that can be used on the QPixmap widget.
|width()||Returns the width of the image|
|height()||Returns the height of the image|
|load(filename)||Takes a filepath or filename as a parameter, from which it loads image data.|
|save(filename)||Saves to your device the image in QPixmap, to a file specified by “filename”.|
You can learn more about the QPixmap widget from the official PyQt documentation here.
This marks the end of the PyQt5 QPixmap article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.