QPixmap maintain aspect ratio

后端 未结 2 1255
广开言路
广开言路 2021-01-03 09:54

I\'m writing a program that will allow me to upload photos to TUMBLR via their API, I\'ve got the uploading working (thanks to you guys).

I\'ve put a \'queueBox\' on

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 10:55

    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.

提交回复
热议问题