Sunday, September 1, 2013

PyQt4: Widget that holds an image and a quit button

I made an extension to the WidgetWithQuit class I introduced recently in this post.
It now can hold an image (input should be a 2D or 3D numpy.ndarray). In WidgetWithQuit the quit button would keep its position relative to the bottom right corner. In WidgetWithPictureAndQuit the image displayed is resized likewise: It always keeps the distance to the borders and the quit button while keeping the aspect ratio. If the image, after resizing, is not centered (it happens, when it is not wide enough), it will be centered, such that the distance to the left and right border will be increased.
In addition to the usual imports, you now also need qimage2ndarray which can be installed via pip.
Please note that in order to make the example shown below work you will need the code introduced in my recent post.

from qimage2ndarray import array2qimage

class WidgetWithPictureAndQuit(WidgetWithQuit):
    def __init__(self, parent=None, buttontext="Quit", margin=10, image=None):
        WidgetWithQuit.__init__(self, parent, buttontext, margin)
        self.image = array2qimage(image)
        self.label = QtGui.QLabel(self)
        if self.image is not None:
            self.resize_image()

    def resize_image(self):
        widget_geometry = self.geometry()
        button_geometry = self.quit_button.geometry()
        width = widget_geometry.width() - 2*self.margin
        height = widget_geometry.height() - (button_geometry.height() + 3*self.margin)
        width_offset = self.margin
        pixmap = QtGui.QPixmap.fromImage(self.image).scaled(width, height, QtCore.Qt.KeepAspectRatio)
        if pixmap.width() < width:
            width_offset = (widget_geometry.width() - pixmap.width())/2
        self.label.setGeometry(width_offset, self.margin, width, height)
        self.label.setPixmap(pixmap)

    def resizeEvent(self, event):
        WidgetWithQuit.resizeEvent(self, event)
        self.resize_image()

No comments:

Post a Comment