Python 如何设置像素贴图的最大宽度和高度?

Python 如何设置像素贴图的最大宽度和高度?,python,qt,pyqt,pyside,pixmap,Python,Qt,Pyqt,Pyside,Pixmap,我有一个显示图像的窗口,如下所示: import sys from PyQt4 import QtGui class Window(QtGui.QWidget): def __init__(self): super(Window, self).__init__() self.initUI() def initUI(self): pixmap = QtGui.QPixmap("image.jpg") pix

我有一个显示图像的窗口,如下所示:

import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        pixmap = QtGui.QPixmap("image.jpg")

        pixmapShow = QtGui.QLabel(self)
        pixmapShow.setPixmap(pixmap)

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(pixmapShow, 0, 1)

        self.setGeometry(400, 400, 400, 400)
        self.setWindowTitle('Review')    
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())
如何设置显示像素贴图所允许的最大宽度和最大高度

  • 如果图像宽于350像素或高于200像素,则应缩小图像,直到一维等于350像素,并保持纵横比
  • 如果图像小于350x200,则不会发生缩放

您可以定义自己的Pixmap容器类,该类根据resize事件自动缩放Pixmap

class PixmapContainer(QtGui.QLabel):
    def __init__(self, pixmap, parent=None):
        super(PixmapContainer, self).__init__(parent)
        self._pixmap = QtGui.QPixmap(pixmap)
        self.setMinimumSize(1, 1)  # needed to be able to scale down the image

    def resizeEvent(self, event):
        w = min(self.width(), self._pixmap.width())
        h = min(self.height(), self._pixmap.height())
        self.setPixmap(self._pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio))
那么在你的代码中,它是非常直截了当的:

def initUI(self):

    pixmapShow = PixmapContainer("image.jpg")
    pixmapShow.setMaximumSize(350, 200)

    grid = QtGui.QGridLayout(self)
    grid.setSpacing(10)
    grid.addWidget(pixmapShow, 0, 1)

    self.setGeometry(400, 400, 400, 400)
    self.setWindowTitle('Review')    
    self.show()