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

标签 qt pyside qlistview

我试图使设置为 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

看起来像这样:

different rowHeight dependent on imageSize

关于qt - QListView 可以有不同的垂直和水平间距吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700948/

相关文章:

c++ - Qt Creator 中使用 opencv 的程序意外崩溃

python - 如何计算 QTreeWidget 内容的高度?

c++ - QListView & QStandardItemModel 在编辑行之前检查文本

python - 在您的系统上找不到 MSVC 编译器版本 10.0

python - PyQt 或 PySide - 使用哪一个

c++ - 防止所选项目在 QListView 中超出 View

qt - 如何清除QListView的所有项目

qt - 如何使用自定义(不可编辑)委托(delegate)创建模型/ View TableView?

c++ - 如何使用 OpenGL 渲染在 Qt 界面上显示 IPLImage 流?

python - setItemWidget 导致崩溃