Skip to content

Instantly share code, notes, and snippets.

@stlehmann
Last active August 29, 2015 13:57
Show Gist options
  • Save stlehmann/9912341 to your computer and use it in GitHub Desktop.
Save stlehmann/9912341 to your computer and use it in GitHub Desktop.
Display an Image in a QTableView cell via a Model and scale the image depending on the cell size.
IMAGE, NAME, SHOP = range(COLUMN_COUNT)
class MyItem(object):
def __init__(self, name, image_filename, price)
self.name = name
self.price = price
self.image = QPixmap()
self.image.load(image_filename)
class ArticleListModel(QAbstractTableModel):
def __init__(self, parent=None):
super().__init__(parent)
self.items = [MyItem("item1", "image1.jpg", 15.99), MyItem("item2", "image2.jpg", 120.00]
self.table = None
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
item = self.items[index.row()]
if role == Qt.DecorationRole:
if column == IMAGE:
if item.image is None:
return QVariant()
#Scale the image to cell size if larger
#----------------------------------------------------
row_height = self.table.rowHeight(index.row())
column_width = self.table.columnWidth(index.column())
img = item.image
#scale height
if img.height() > row_height:
img = img.scaledToHeight(row_height)
#scale width
if img.width() > column_width:
img = img.scaledToWidth(column_width)
return img
return QVariant()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment