qt - Resizable PyQt widget displaying an image with fixed aspect ratio -
it common problem display qimage in widget. while can done using qlabel.setpixmap
, resulting qlabel have fixed size equal size of pixmap. possible use setscaledcontents
make qlabel scale pixmap , allow resizing. however, ignore aspect ratio of image , scale pixmap fill whole label.
several other questions on stackoverflow ask solutions problem, , typical solution given re-scale pixmap using qpixmap.scaled()
depending on size of widget:
- qpixmap maintain aspect ratio python
- how make image resize scale in qt?
- qt: resizing qlabel, containing qpixmap, while keeping it's aspect ratio
is there different, more "native" way achieve this?
the following qlabel-based widget preserve aspect ratio of pixmap assigned it. uses heighforwidth
method return preferred height of widget given width. way, widget naturally respects aspect ratio of pixmap when resized , scales accordingly. tested in pyqt5.
class imagewidget(qlabel): def __init__(self, parent=none): super().__init__(parent) self.setscaledcontents(true) def hasheightforwidth(self): return self.pixmap() not none def heightforwidth(self, w): if self.pixmap(): return int(w * (self.pixmap().height() / self.pixmap().width()))
Comments
Post a Comment