I have a QTableView to display some informations of a database in the form of a grid. One of the fields is a path to an image and I would like to display these images in my table.
I tried something with a delegate, but I'm not really confortable with them and I couldn't get anything working. I also tried something with the role :
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
This piece of code is inspired by something I found in another forum and that was supposed to work. However it doesn't do anything for me, only slows down the execution of my code.
Any idea why it's not working ? If you have an example with a delegate I'd appreciate it also!
Thanks for your attention
RESOLVED: I got it working with a custom delegate. Here is my code if someone's interested :
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)
Thank you for the solution and the code example, Johanna. It was a huge help.
In addition, in case anyone else needs it spelled out like I did:
1) Set the item delegate for the image-bearing column of your QTableView (I did this in myTableView.init()) like so:
self.setItemDelegateForColumn(1, yourImageDelegate(parent))
2) In yourImageDelegate class, you may want to overload sizeHint() for the size of your image like so:
def sizeHint(self, option, index) :
return QSize(160, 90) # whatever your dimensions are
Swoot!
when i test , i use drawPixmap(option.rect.x(), option.rect.y(), pixmap) to draw icon, noneed do 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With