我试图使设置为 IconMode 的 QListView 具有不同的水平和垂直间距。使用这个类可以实现这一点吗?
此外,我的所有图标都具有相同的宽度,但它们的高度发生变化,我希望 View 能够适应这些不同的尺寸。
最佳答案
两者都可以通过QStyledItemDelegate()
来完成。在我的示例(pyqt5)中 model.data()
返回图标的路径,所有图标的宽度均为 100。 sizeHint()
的返回值取决于项目图标的高度以及垂直和水平间距:
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()将委托(delegate)设置为 View
看起来像这样:
关于qt - QListView 可以有不同的垂直和水平间距吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700948/