python - Resizing QPixmap while maintaining aspect ratio -
to keep aspect ratio of image fixed while resizing qdialog
i've tried following:
import os, sys pyqt5.qtwidgets import qapplication, qdialog, qgridlayout, qlabel pyqt5.qtgui import qpixmap pyqt5.qtcore import qt class dialog(qdialog): def __init__(self, parent=none): super(dialog, self).__init__(parent) self.pic = qlabel() self.pic.resizeevent = onresize self.pic.setpixmap(qpixmap(os.getcwd() + "/images/1.jpg").scaled(300, 200, qt.keepaspectratio,qt.smoothtransformation)) layout = qgridlayout() layout.addwidget(self.pic, 1, 0) self.setlayout(layout) def onresize(event): size = dialog.pic.size() dialog.pic.setpixmap(qpixmap(os.getcwd() + "/images/1.jpg").scaled(size, qt.keepaspectratio, qt.smoothtransformation)) if __name__ == '__main__': app = qapplication(sys.argv) dialog = dialog() dialog.show() sys.exit(app.exec_())
as espected image starts 300x200. can enlarged wished size can't reduced @ (down 300x200 after enlargement). onresize
seems lack something.
i have working example problem. don't use setpixmap
method draw pixmap on widget, draw reimplementing paintevent
of widget.
from pyqt4 import qtgui, qtcore import sys pyqt4.qtcore import qt class label(qtgui.qlabel): def __init__(self, img): super(label, self).__init__() self.setframestyle(qtgui.qframe.styledpanel) self.pixmap = qtgui.qpixmap(img) def paintevent(self, event): size = self.size() painter = qtgui.qpainter(self) point = qtcore.qpoint(0,0) scaledpix = self.pixmap.scaled(size, qt.keepaspectratio, transformmode = qt.smoothtransformation) # start painting label left upper corner point.setx((size.width() - scaledpix.width())/2) point.sety((size.height() - scaledpix.height())/2) print point.x(), ' ', point.y() painter.drawpixmap(point, scaledpix) class main(qtgui.qwidget): def __init__(self): super(main, self).__init__() layout = qtgui.qgridlayout() label = label(r"/path/to/some/image.png") layout.addwidget(label) layout.setrowstretch(0,1) layout.setcolumnstretch(0,1) self.setlayout(layout) self.show() if __name__ =="__main__": app = qtgui.qapplication(sys.argv) widget = main() sys.exit(app.exec_())
copy whole code , run is. try scale window appears. understand paintevent
in label
class. dont forget change path existing png image in __init__
of main
class.
update changing image:
to change image can add method changepixmap(self, img)
label
class , call on event on want change pixmap.
... def changepixmap(self, img): self.pixmap = qtgui.qpixmap(img) self.repaint() # repaint() trigger paintevent(self, event), way new pixmap drawn on label
you can call method main
class saving reference label
class in member variable.
... self.label = label('/path/to/image.png') ...
then inside event in main
class, call self.label.changepixmap('path/to/new/image.png')
Comments
Post a Comment