Source

pilpreview / delegates.py

# -*- coding: utf-8 -*-

# Copyright 2008-2012 Alexandre `Zopieux` Macabies
# This module is part of avatarsio and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

from PySide import QtCore, QtGui

class ListviewDelegate(QtGui.QStyledItemDelegate):
    maxPixmapSize = (200, 200)
    imageRole = QtCore.Qt.UserRole + 1
    isThumbRole = QtCore.Qt.UserRole + 2

    def _get_element_rects(self, option, index):
        name = index.data(QtCore.Qt.DisplayRole)
        image = index.data(self.imageRole)
        font = index.data(QtCore.Qt.FontRole)
        fm = QtGui.QFontMetrics(font)

        nameRect = QtCore.QRect(option.rect)
        bd = fm.boundingRect(name)
        nameRect.setWidth(fm.width(name))
        nameRect.setHeight(fm.height())
        nameRect.adjust(4, 4, 4, 4)

        if index.data(self.isThumbRole) and (image.width(), image.height()) > self.maxPixmapSize:
            # we scale only if 1. it's thumb and 2. larger than maxSize
            image = image.scaled(*self.maxPixmapSize, aspectMode=QtCore.Qt.KeepAspectRatio, mode=QtCore.Qt.SmoothTransformation)

        imageRect = QtCore.QRect(option.rect)
        imageRect.setWidth(image.width())
        imageRect.setHeight(image.height())
        imageRect.moveTop(nameRect.bottom())
        imageRect.adjust(4, 4, 4, 4)

        return nameRect, imageRect

    def sizeHint(self, option, index):
        nameRect, imageRect = self._get_element_rects(option, index)
        return nameRect.united(imageRect).size()

    def paint(self, painter, option, index):
        name = index.data(QtCore.Qt.DisplayRole)
        image = index.data(self.imageRole)
        font = index.data(QtCore.Qt.FontRole)

        nameRect, imageRect = self._get_element_rects(option, index)

        painter.save()
        painter.drawImage(imageRect, image)
        painter.setFont(font)
        painter.drawText(nameRect, name)
        painter.restore()