PyQt/Qt: How to stretch an image in Qlabel widget?

pyqt, qt

Solution

You need to call `self.label.setScaledContents(true);`. So that `QLabel` will resize itself to the size of pixmap/image and scroll-bar will get visible. See this documentation.

Problem

I want to display an image in my app. I use QtDesigner to design UI, then use pyqt to coding. The problem is the image that will be shown is lager than the widget size on the UI. I refer to offical demo: QT - Widget Image Viewer Demo add imagelabel and scrollArea, code as follows: ``` ---- UI init ---- self.label = QtGui.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(40, 140, 361, 511)) self.label.setSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Preferred) self.label.setObjectName(_fromUtf8("label")) self.scrollArea = QtGui.QScrollArea(self.centralwidget) self.scrollArea.setGeometry(QtCore.QRect(40, 140, 361, 511)) self.scrollArea.setWidget(self.label) self.scrollArea.setObjectName(_fromUtf8("scrollArea")) ---- function ---- filename = "./Penguins.jpg" image = QtGui.QImage(filename) pp = QtGui.QPixmap.fromImage(image) lbl = QtGui.QLabel(self.label) lbl.setPixmap(pp) self.scrollArea.setWidgetResizable(True) lbl.show() ``` but it doesn't stretch the image, even no scroll bar appear!

Original source

Related problems