I am trying to make a QListView set to IconMode have a different spacing horizontally and vertically. Can this be achieved using this class?
Also, all of my icons have the same width but they change in height and I would like the view to adapt to these different sizes.
both can be done by QStyledItemDelegate()
. In my example (pyqt5) model.data()
returns the path of the icons, all icons have a width of 100. The return-value of sizeHint()
depends on the height of the items icon and vertical- and horizontalSpacing:
class MyDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self):
QtWidgets.QItemDelegate.__init__(self)
self.pen= QtGui.QPen(QtGui.QColor(0,0,0))
self.imageWidth = 100
self.horizontalSpacing = 5
self.verticalSpacing = 10
def sizeHint(self, option, index):
width = self.imageWidth + 2*self.horizontalSpacing
height = QtGui.QImage(index.data()).height() + 2*self.verticalSpacing
return QtCore.QSize(width, height)
def paint(self, painter, option, index):
border = option.rect # item.rect in the view
image = QtGui.QImage(index.data()) # model.data() returns the path of the imagefile
painter.save()
painter.setPen(self.pen)
painter.drawRect(border)
painter.drawImage(QtCore.QPointF(border.x() + self.horizontalSpacing, border.top() + self.verticalSpacing), image)
painter.restore()
set the delegate to the view by setItemDelegate()
looks like this: