Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt

pyqt

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!

like image 812
whuiscool Avatar asked Jun 06 '12 13:06

whuiscool


People also ask

How do I add an image to a QLabel in Qt?

ui->label->setStyelSheet("image:url(:/1. png); border-image:url(:/2. png);");

How do I resize an image in QPixmap?

You can scale the pixmap by keeping its aspect ratio every time it changes: QPixmap p; // load pixmap // get label dimensions int w = label->width(); int h = label->height(); // set a scaled pixmap to a w x h window keeping its aspect ratio label->setPixmap(p. scaled(w,h,Qt::KeepAspectRatio));

How do I add an image to a Qt widget?

The easiest way I've seen so on : You drag and drop your Label on your window, select the Label, you'll see on the right side of your screen the 'Property Editor' frame and the 'QLabel' menu, you click on pixmap => Choose File..., select a file and that's it.

How do I display an image in QT design?

Using Qt DesignerDrag this onto the QMainWindow to add it. Next, with the Label selected, look in the right hand QLabel properties panel for the pixmap property (scroll down to the blue region). From the property editor dropdown select "Choose File…" and select an image file to insert.


1 Answers

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.

like image 69
Ammar Avatar answered Nov 15 '22 10:11

Ammar