6

我有一个 QTableView 以网格的形式显示数据库的一些信息。其中一个字段是图像的路径,我想在我的表格中显示这些图像。

我和一个代表一起尝试了一些东西,但我对他们不太满意,而且我什么也做不了。我还尝试了角色:

    if index.column() == 4:
        if role == QtCore.Qt.DecorationRole:
            label = QtGui.QLabel()
            path = "path/to/my/picture.jpg"
            image = QtGui.QImage(str(path)) 
            pixmap = QtGui.QPixmap.fromImage(image)
            label.setPixmap(pixmap)
            return label

这段代码的灵感来自我在另一个论坛上发现的东西,并且应该可以工作。但是它对我没有任何作用,只会减慢我的代码的执行速度。

知道为什么它不起作用吗?如果您有代表的示例,我也将不胜感激!

感谢您的关注

已解决:我让它与自定义委托一起工作。如果有人感兴趣,这是我的代码:

class ImageDelegate(QtGui.QStyledItemDelegate):

    def __init__(self, parent):
        QtGui.QStyledItemDelegate.__init__(self, parent)

    def paint(self, painter, option, index):        

        painter.fillRect(option.rect, QtGui.QColor(191,222,185))

        # path = "path\to\my\image.jpg"
        path = "araignee_de_mer.jpg"

        image = QtGui.QImage(str(path))
        pixmap = QtGui.QPixmap.fromImage(image)
        pixmap.scaled(50, 40, QtCore.Qt.KeepAspectRatio)
        painter.drawPixmap(option.rect, pixmap) 
4

3 回答 3

4

感谢您提供解决方案和代码示例,Johanna。这是一个巨大的帮助。

此外,以防其他人需要像我一样拼写:

1) 为 QTableView 的图像承载列设置项目委托(我在 myTableView.init() 中执行此操作),如下所示:

self.setItemDelegateForColumn(1, yourImageDelegate(parent))

2) 在 yourImageDelegate 类中,您可能希望像这样为图像大小重载 sizeHint() :

def sizeHint(self, option, index) :
    return QSize(160, 90) # whatever your dimensions are

嗖嗖嗖!

于 2011-12-08T20:14:24.983 回答
2

当我测试时,我使用 drawPixmap(option.rect.x(), option.rect.y(), pixmap) 来绘制图标,不需要 pixmap.scaled。

class ImageDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent=None):
        QtGui.QStyledItemDelegate.__init__(self, parent)
        #self.icon =icon
    def paint(self, painter, option, index):
        #painter.fillRect(option.rect, QtGui.QColor(191,222,185))
        # path = "path\to\my\image.jpg"
        path = "icon1.png"
        image = QtGui.QImage(str(path))
        pixmap = QtGui.QPixmap.fromImage(image)
        #pixmap.scaled(16, 16, QtCore.Qt.KeepAspectRatio)
        # when i test ,just use option.rect.x(), option.rect.y(), no need scaled 
        painter.drawPixmap(option.rect.x(), option.rect.y(),  pixmap)
于 2014-09-02T03:06:42.157 回答
0

我认为您不需要将 Pixmap 封装在标签或图像中。尝试只返回像素图。

if index.column() == 4:
    if role == QtCore.Qt.DecorationRole:            
        path = "path/to/my/picture.jpg"
        pixmap = QtGui.QPixmap(path) 
        return pixmap
于 2011-06-24T12:27:02.257 回答