我有一个显示图像的窗口,如下所示:
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_())
如何设置显示像素图所允许的最大宽度和最大高度?
答案 0 :(得分:2)
您可以定义自己的Pixmap容器类,它会根据resize事件自动缩放像素图。
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()