[ACCEPTED]-QPixmap maintain aspect ratio-qlabel
Get rid of the
self.myLabel.setScaledContents(True)
call (or set it to False). It 19 is filling your widget with the pixmap without 18 caring about the aspect ratio.
If you need 17 to resize a QPixmap
, as you have found, scaled
is the 16 required method. But you are invoking it 15 wrong. Let's look at the definition:
QPixmap QPixmap.scaled (self,
int width,
int height,
Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio,
Qt.TransformationMode transformMode = Qt.FastTransformation)
Return 14 type of this function is QPixmap
, so it returns 13 a scaled copy of the original pixmap.
Then you 12 need a width
and a height
, describing the (maximum) final 11 size of the pixmap.
Two more optional parameters. aspectRatioMode
deals 10 with the, well aspect ratio. The documentation details 9 the different options and their effects. transformMode
defines 8 how (which algorithm) the scaling is done. It 7 might change the final quality of your image. You 6 probably don't need this one.
So, putting 5 it together you should have (Qt
namespace 4 is inside QtCore
):
# substitute the width and height to desired values
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(width, height, QtCore.Qt.KeepAspectRatio))
Alternatively, if you have a 3 fixed size QLabel
, you could call the .size()
method 2 to get the size from it:
self.myLabel.setPixmap(QtGui.QPixmap(_fromUtf8(directory + '\\' + tempName)).scaled(self.myLabel.size(), QtCore.Qt.KeepAspectRatio))
Note: You might want 1 to use os.path.join(directory, tempName)
for the directory + '\\' + tempName
part.
PyQt5 code change update:
The above answer 13 of avaris needed a PyQt5 update because it breaks.
QPixmap.scaled (self, int width, int height, Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio
Keeping 12 the self
in the code results in below traceback 11 error.
TypeError: arguments did not match 10 any overloaded call: scaled(self, int, int, aspectRatioMode: Qt.AspectRatioMode 9 = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode 8 = Qt.FastTransformation): argument 1 has 7 unexpected type 'MainUI' scaled(self, QSize, aspectRatioMode: Qt.AspectRatioMode 6 = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode 5 = Qt.FastTransformation): argument 1 has 4 unexpected type 'MainUI'
Thus this should 3 be (without "self", "Qt") as 2 stated below:
QPixmap.scaled (int width, int height, aspectRatioMode = IgnoreAspectRatio
or:
QPixmap.scaled (int width, int height, aspectRatioMode = 0)
KeepAspectRatio = 2... but 1 used as provided by aspectRatioMode = 2
in above code. Enjoy!
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.