2

I want to color a cell in a QTableView.

So I'm trying to change the itemData of the corresponding item in the associated QTableModel.

To do so, I use the setItemData method of the QAbstractTableModel class.

In the documentation :

QAbstractItemModel::setItemData(const QModelIndex & index, const QMap < int, QVariant > & roles)

This is my piece of code :

color = QtGui.QColor(Qt.red)
self.model.setItemData(self.model.index(3,3),color,Qt.BackgroundRole)

I thought this would color the third cell of the model (horizontally and vertically) in red.

But the application answers :

TypeError: QAbstractItemModel.setItemData(QModelIndex, dict-of-int-QVariant): argument 2 has unexpected type 'QColor'

If I try to transform the Qcolor type in a Qvariant :

color = Qt.QVariant(QtGui.QColor(Qt.red))
self.model.setItemData(self.model.index(3,3),color,Qt.BackgroundRole)

Answer :

TypeError: PyQt4.QtCore.QVariant represents a mapped type and cannot be instantiated

Which I really can't understand.

So there is my question : which type of data must I put in the second parameter of a setItemData method?

Thanks for advance

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
V Damoy
  • 190
  • 10

1 Answers1

1

You should use QAbstractItemModel::setData to set a single value in the itemData map.

self.model.setData(self.model.index(3,3),color,Qt.BackgroundRole)

You can use QAbstractItemModel::setItemData if you want to set many values at once, but have to build a QMap where each couple is composed by a role and its corresponding value:

 QMap<int, QVariant> map;
 map.insert(Qt::BackgroundRole, color);
 self.model.setItemData(self.model.index(3,3), map);
p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • Thank you very much p-a-o-l-o! Thanks to you, I finally understood how setItemData works. I've used setData, and the error message is gone. The (3,3) cell has not changed color, but it's another problem! ;-) This one is resolved. – V Damoy Dec 22 '17 at 11:39