QListView可以有不同的垂直和水平间距吗?

时间:2015-09-21 17:11:07

标签: qt pyside qlistview

我试图让设置为IconMode的QListView在水平和垂直方向上有不同的间距。这可以用这个课程来实现吗?

此外,我的所有图标都具有相同的宽度,但它们的高度会发生变化,我希望视图能够适应这些不同的尺寸。

1 个答案:

答案 0 :(得分:1)

两者都可以由QStyledItemDelegate()完成。在我的示例中(pyqt5)model.data()返回图标的路径,所有图标的宽度均为100. sizeHint()的返回值取决于项目图标的高度以及vertical-和horizo​​ntalSpacing:

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()

通过setItemDelegate()

将委托设置为视图

看起来像这样:

different rowHeight dependent on imageSize