Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt:How do I display a image properly?

Tags:

python

pyqt

I want to display an image in pyqt so,i used a label and the pixmap option,and the scaledContents but the image is distorted.Should I use another widget or do something else? Thanks.

This is the code:

from PyQt4 import QtCore, QtGui
self.label.setPixmap(QtGui.QPixmap(_fromUtf8('image.jpg')))
self.label.setScaledContents(True)

I use QtDesigner.

I tried this: self.label.pixmap().scaled(QtCore.QSize(self.label.size()), QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)

but the images don't get resized to fit the label.

like image 788
IordanouGiannis Avatar asked Dec 31 '11 11:12

IordanouGiannis


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 add an image to 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.

What is a widget in PyQt?

Widgets are the basic building blocks for graphical user interface (GUI) applications built with Qt. Each GUI component (e.g. buttons, labels, text editors) is a widget that is placed somewhere within a user interface window, or is displayed as an independent window.

Do I need Qt to use PyQt?

Your PyQt6 license must be compatible with your Qt license. If you use the GPL license, then your code must also use a GPL-compatible license.


1 Answers

Use the scaled(const QSize, Qt::AspectRatioMode, Qt::TransformationMode) method of the pixmap, it has an option Qt::KeepAspectRatio that does not deform the image. The default is to ignore the aspect ratio

Also, note that the scaled method returns the scaled pixmap, so it must be used this way:

myPixmap = QtGui.QPixmap(_fromUtf8('image.jpg'))
myScaledPixmap = myPixmap.scaled(self.label.size(), Qt.KeepAspectRatio)
self.label.setPixmap(myScaledPixmap)
like image 55
Gianluca Avatar answered Sep 28 '22 22:09

Gianluca