QAbstractItemDelegate.paint seems to be called with wrong option.rect
-
I'm trying to have QListView to display some images in a list. Because I also want to add some custom look to those images, I'm using custom item delegate.
Most of it is pretty standard. I have class inheriting from
QAbstractItemDelegate
and set object of this class as QListView's delegate.
I want size of images adjust to the list widget, which can be resized by user.I implement sizeHint, so images scale with the widget
def sizeHint(self, option: QStyleOptionViewItem, index: Union[QModelIndex, QPersistentModelIndex]) -> QSize: widget: QListView = option.widget image = index.model().data(index, Qt.DisplayRole) height = option.widget.height() - widget.spacing() * 2 width = image.scaled_width(height) return QSize(width, height)
and here's my paint
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: Union[QModelIndex, QPersistentModelIndex]) -> None: image: ImageInfo = index.model().data(index, Qt.DisplayRole) qimg = image.qimage(option.rect.size()) # gets image scaled to proper size painter.drawImage(option.rect, qimg)
This code works fine as long I don't resize the view. When I do resize it, images scale, but don't change their position. Especially
option.rect
has proper width and height, but x always stays the same. So, if we resize widget, so it's bigger, images will grow, but stay on the same positions and in result start obscure each other. Any idea why this is happening and how I might be able to fix it? -
Hi,
Just thinking quickly, shouldn't you adjust the rect position based on the index row ?
By the way, I think you should use QStyledItemDelegate as base class for your delegate since it's the default class used for the item views.
-
Hi,
Just thinking quickly, shouldn't you adjust the rect position based on the index row ?
By the way, I think you should use QStyledItemDelegate as base class for your delegate since it's the default class used for the item views.
@SGaist said in QAbstractItemDelegate.paint seems to be called with wrong option.rect:
Just thinking quickly, shouldn't you adjust the rect position based on the index row ?
In this case, images can have different aspect ratios, so I'd need ratio of each image before current one to calculate where to paint it. (It can be done, but seems to be going against design of delegate.)
More importantly, values of rect seem to still affect how mouse events are handled, so even if I'd adjust paintings, selecting element's would work on offsets defined by rect and click event's wouldn't work properly.
By the way, I think you should use QStyledItemDelegate as base class for your delegate since it's the default class used for the item views.
Thanks for the tip!