QPixmap maintain aspect ratio

心已入冬 提交于 2019-11-30 16:10:23

Get rid of the

self.myLabel.setScaledContents(True)

call (or set it to False). It is filling your widget with the pixmap without caring about the aspect ratio.

If you need to resize a QPixmap, as you have found, scaled is the required method. But you are invoking it 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 type of this function is QPixmap, so it returns a scaled copy of the original pixmap.

Then you need a width and a height, describing the (maximum) final size of the pixmap.

Two more optional parameters. aspectRatioMode deals with the, well aspect ratio. The documentation details the different options and their effects. transformMode defines how (which algorithm) the scaling is done. It might change the final quality of your image. You probably don't need this one.

So, putting it together you should have (Qt namespace 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 fixed size QLabel, you could call the .size() method 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 to use os.path.join(directory, tempName) for the directory + '\\' + tempName part.

PyQt5 code change update:

The above answer of avaris needed a PyQt5 update because it breaks.

QPixmap.scaled (self, int width, int height, Qt.AspectRatioMode aspectRatioMode = Qt.IgnoreAspectRatio

Keeping the self in the code results in below traceback error.

TypeError: arguments did not match any overloaded call: scaled(self, int, int, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'MainUI' scaled(self, QSize, aspectRatioMode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio, transformMode: Qt.TransformationMode = Qt.FastTransformation): argument 1 has unexpected type 'MainUI'

Thus this should be (without "self", "Qt") as stated below:

QPixmap.scaled (int width, int height, aspectRatioMode = IgnoreAspectRatio

or:

QPixmap.scaled (int width, int height, aspectRatioMode = 0)

KeepAspectRatio = 4... but used as provided by aspectRatioMode = 4 in above code. Enjoy!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!