Domanda

I have a QStandardItemModel assigned to a QTableView I want to change the color of each row based on the value of the column #5 of the model :

class MyStandardTableModel(QtGui.QStandardItemModel):
    def __init__(self, headerdata, parent=None, *args):
        QtGui.QStandardItemModel.__init__(self, parent, *args)
        self.headerdata = headerdata

    def data(self, index, role):
        if not index.isValid():
            return QtCore.QVariant()
        elif role != QtCore.Qt.DisplayRole:
            if role == QtCore.Qt.TextAlignmentRole:
                return QtCore.Qt.AlignHCenter
            if role == QtCore.Qt.BackgroundRole:
                status = index.sibling(index.row(), 5).data().toInt()[0]
                if status == 1:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
                if status == 2:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
        return QtGui.QStandardItemModel.data(self, index, role)

...

And the function for changing color (just rows 1 and 2 for testing) :

def changeColor(self, model):
    model.setData(model.index(1, 5), 1)
    model.setData(model.index(2, 5), 2)

For now, the rows doesn't change immediatly when I call the changeColor function but change when I call the function and scroll over the QTableView.

I think I must emit a signal in the changeColor but I don't know which one. Also, maybe it have a proper way to do this.

È stato utile?

Soluzione

Ok, found the solution.

The signal to be emitted is dataChanged(QModelIndex,QModelIndex). I thought it was emitted by the setData function but in fact not.

Changing the changeColor function by :

def changeColor(self, model):
    model.setData(model.index(1, 5), 1)
    model.setData(model.index(2, 5), 2)
    model.emit(QtCore.SIGNAL('dataChanged(QModelIndex,QModelIndex)'), model.index(1, 5), model.index(2, 5))

solves the problem.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top