self.icon = 'ico.png' item = QTableWidgetItem(QtGui.QIcon(self.icon), "") item.setData(Qt.DecorationRole, item) self.table_widget.setItem(0, 0, item) 

And when I wrap it in DisplayRole, it shows, but I need it in the DecorationRole to save it later.

  • Try replacing item.setData(Qt.DecorationRole, item) with item.setData(Qt.DecorationRole, QtGui.QIcon(self.icon)) - янв
  • Thanks helped! - Dr.robot

1 answer 1

According to the documentation :

  • Qt.DisplayRole requires that the passed object be Qt.DisplayRole to a QString type (string).
  • Qt.DecorationRole requires that the transmitted object be Qt.DecorationRole to one of the following three types: QColor (color), QIcon (icon), QPixmap (image).

The problem is that the QTableWidgetItem to a string only . As a result, the wrapper element returns an empty string for setData() instead of an image.

To solve this problem, you need to remove the wrapper over the QIcon instance and transfer the image directly:

 self.icon = 'ico.png' item = QTableWidgetItem(QtGui.QIcon(self.icon), "") item.setData(Qt.DecorationRole, QtGui.QIcon(self.icon)) self.table_widget.setItem(0, 0, item)